Click here to Skip to main content
15,868,014 members
Articles / Database Development / SQL Server

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

Rate me:
Please Sign up or sign in to vote.
4.71/5 (13 votes)
28 Apr 2010CPOL1 min read 112.6K   39   16
Some frequently-used methods for image handling in .NET

Sooner or later, you will find the need for 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
  • Converting binary data back to image

Save an Image

C#
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

C#
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);
    }
    else
    {
        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.)

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

Resize the Image and Keep Aspect Ratio

C#
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

C#
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);
    fileStream.Close();
    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.

C#
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 http://x189.blogspot.com/feeds/posts/default

License

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

 
QuestionHelpful Pin
Baghmirani16-Aug-22 19:42
Baghmirani16-Aug-22 19:42 
PraiseThank + little impro Pin
Member 126222099-Jul-16 17:00
Member 126222099-Jul-16 17:00 
QuestionMessage Closed Pin
26-Oct-14 22:59
andyadams26-Oct-14 22:59 
AnswerRe: Convert varbinary(max) to image,resize and save it in a folder using c# or vb.net? Pin
Garth J Lancaster26-Oct-14 23:20
professionalGarth J Lancaster26-Oct-14 23:20 
SuggestionCan I get the working project Pin
sudarson mothilal9-Feb-14 17:49
sudarson mothilal9-Feb-14 17:49 
AnswerRe: Can I get the working project Pin
Duy H. Thai10-Feb-14 4:08
Duy H. Thai10-Feb-14 4:08 
Question[My vote of 1] Very poorly written Pin
msdevtech27-Feb-13 7:43
msdevtech27-Feb-13 7:43 
GeneralMy vote of 4 Pin
Kirans21-Dec-11 22:44
Kirans21-Dec-11 22:44 
GeneralRe: My vote of 4 Pin
Duy H. Thai22-Dec-11 2:55
Duy H. Thai22-Dec-11 2:55 
GeneralMy vote of 5 Pin
kraftspl5-Aug-10 11:02
kraftspl5-Aug-10 11:02 
GeneralThank you for sharing Pin
rctaubert4-May-10 1:47
rctaubert4-May-10 1:47 
Thank you for sharing this. My next project will be an image viewer and this will be valuable to have.

I need to covert this to VB.net. Are there any problems you might be aware of?

Thank you,
GeneralRe: Thank you for sharing Pin
Duy H. Thai4-May-10 5:41
Duy H. Thai4-May-10 5:41 
GeneralRe: Thank you for sharing Pin
Kirans21-Dec-11 22:45
Kirans21-Dec-11 22:45 
GeneralI don't have FromStream definition Pin
Yerko_lion3-May-10 2:47
Yerko_lion3-May-10 2:47 
AnswerRe: I don't have FromStream definition Pin
Duy H. Thai3-May-10 6:10
Duy H. Thai3-May-10 6:10 
GeneralRe: I don't have FromStream definition Pin
Yerko_lion3-May-10 7:14
Yerko_lion3-May-10 7:14 

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.