Click here to Skip to main content
15,506,025 members
Articles / Programming Languages / C#
Technical Blog
Posted 11 Sep 2010

Tagged as


14 bookmarked

Image in C#: Save, Resize, and Convert to Binary

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
11 Sep 2010CPOL1 min read
Useful methods of handling image in your code, especially when you're working with a database


Sooner or later, you will find the need of handling image in your code, especially when you're working with a database. So in this article, I share with you some useful methods that I find myself using frequently. They include: saving image in a folder, getting thumbnail from the original image, converting image to binary for saving in database, and converting binary data back to image.

Save An Image

Image originalImage = Image.FromFile(imagePath);
string filePath = AppDomain.CurrentDomain.BaseDirectory + savedName;
originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);

This code saves the image to the base directory of your app or website.
imagePath is the full path to the image that we need to save (e.g. "C:\Pictures\Lighthouse.jpg"), one way to get this is use an OpenFileDialog.
savedName is the name for the saved image.

Save the Image as a Thumbnail

public static void SaveImage(string imagePath, string savedName,
    int width = 0, int height = 0)
    Image originalImage = Image.FromFile(imagePath);
    string filePath = AppDomain.CurrentDomain.BaseDirectory + savedName;

    if (width > 0 && height > 0)
        Image.GetThumbnailImageAbort myCallback = 
		new Image.GetThumbnailImageAbort(ThumbnailCallback);
        Image imageToSave = originalImage.GetThumbnailImage
			(width, height, myCallback, IntPtr.Zero);
        imageToSave.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        originalImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
private static bool ThumbnailCallback() { return false; }

Note the parameters: int width = 0 & int height = 0. This is a C# 4.0 feature: Optional Parameters, so we can call this method like this: (assume this method is in the ImageHandling class).

// Save image as original
ImageHandling.SaveImage(@"C:\Pictures\Lighthouse.jpg", "OriginalLighthouse.jpg");
// Save image as thumbnail
		"ThumbnailLighthouse1.jpg", 160, 90);
// New feature: Named Parameter
		"ThumbnailLighthouse2.jpg", height: 90, width: 160);

Resize the Image and Keep Aspect Ratio

int newWidth = originalImage.Width * percentage / 100;
int newHeight = originalImage.Height * percentage / 100;

To keep the image aspect ratio, simply replace width & height parameters with percentage parameter and call the GetThumbnailImage method with our new width & height.

Convert Image to Binary

public static byte[] ImageToBinary(string imagePath)
    FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, (int)fileStream.Length);
    return buffer;

Use this method when you want to save images in your database. The column to store binary data is usually varbinary(MAX).

Convert Binary to Image

You store images in your database as binary, of course you must convert binary back to images so you can display them in your app.

public static Image BinaryToImage(System.Data.Linq.Binary binaryData)
    if (binaryData == null) return null;

    byte[] buffer = binaryData.ToArray();
    MemoryStream memStream = new MemoryStream();
    memStream.Write(buffer, 0, buffer.Length);
    return Image.FromStream(memStream);

You may need to add reference to System.Data.Linq. LINQ-to-SQL maps a varbinary column in your database to its relevant property as System.Data.Linq.Binary.

What about you? What are your favorite image-handling functions? Are there any other functions you'd like to have?

This article was originally posted at


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
Vietnam Vietnam
ASP.NET MVC enthusiast.
Developer @ X189 blog.

Comments and Discussions

GeneralIt looks like exactly the same like this Pin
pewquadrat24-Apr-16 3:28
pewquadrat24-Apr-16 3:28 
GeneralRe: It looks like exactly the same like this Pin
Duy H. Thai26-Apr-16 0:31
Duy H. Thai26-Apr-16 0:31 
Generalmemory stream from byte[] Pin
Richard_N14-Sep-10 15:06
Richard_N14-Sep-10 15:06 
GeneralImage.FromFile locks the file ... [modified] Pin
Blaiser13-Sep-10 21:07
Blaiser13-Sep-10 21:07 
Some nice tips, thanks ...

One point though, Image.FromFile locks the file - in a desktop application, that lock holds until the process exits. I don't know how it affects web apps. An MS knowledge base article says that this behavior is by design. See[^]
Note that the work-around the KB article describes - using FromStream instead of FromFile - does not work reliably.

This presents a problem in a number of our applications. The following is what I use to work around the issue. And yes, I am aware of the irony of posting VB.NET code in response to a C# article ... my appologies to those with VB-phobia ... Wink | ;)


''' <summary>
''' get an image from a file without locking the file via this slightly round-about way
''' </summary>
''' <param name="fileSpec">the full spec of the file from which to load an image</param>
''' <returns>the Image from the passed file or null</returns>
''' <remarks>FromFile locks the file!</remarks>
Public Function GetImageFromFile(ByVal fileSpec As String) As Image

    Dim retImage As Image = Nothing
    Dim bmp As Bitmap = Nothing
    Dim newBmp As Bitmap = Nothing
    Dim gr As Graphics = Nothing

    'if that file exists
    If IO.File.Exists(fileSpec) Then

            'read the file directly into a bitmap via ctor
            bmp = New Bitmap(fileSpec)

            'create a new bitmap with the same dimensions as the image
            newBmp = New Bitmap(bmp.Width, bmp.Height)

            'get a graphics object for the new bitmap, and draw the read bmp into the new bmp
            gr = Graphics.FromImage(newBmp)
            gr.DrawImage(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height), _
                0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel)

            'cleanup the old bitmap
            bmp = Nothing

            'get our final image from the copied bitmap
            retImage = Drawing.Image.FromHbitmap(newBmp.GetHbitmap)

            'log but otherwise ignore errors
        Catch ex As Exception
            LogManager.LogException(ex, "exception loading image file '" & fileSpec & "' via graphics")

            'clean up ...
            If gr IsNot Nothing Then gr.Dispose()
            gr = Nothing
            If newBmp IsNot Nothing Then newBmp.Dispose()
            newBmp = Nothing
            If bmp IsNot Nothing Then bmp.Dispose()
            bmp = Nothing

        End Try

    End If

    Return retImage

End Function

modified on Thursday, September 16, 2010 6:17 AM

GeneralRe: Image.FromFile Pin
N!K!ta10-Nov-10 12:24
N!K!ta10-Nov-10 12:24 
GeneralRe: Image.FromFile Pin
Blaiser10-Nov-10 14:26
Blaiser10-Nov-10 14:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.