Create a thumbnail image from a ByteArray

So you have an image saved to your database as a byte array, below is a neat little method that accepts it as a parameter, converts it to a thumbnail and spit it back out as a byte array.

public static byte[] MakeThumbnail(byte[] myImage, int thumbWidth, int thumbHeight)
{
    using (MemoryStream ms = new MemoryStream())
    using (Image thumbnail = Image.FromStream(new MemoryStream(myImage)).GetThumbnailImage(thumbWidth, thumbHeight, null, new IntPtr()))
    {
        thumbnail.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }
}
Advertisements

Save an Image to a Filestream

In order to save an image to a database, you should first convert it to a byte array using a filestream. Once completed this byte array can be written to your database, usually being stored as a VarBinary DataType. In order to work with filestreams you must first add a reference to System.IO at the top of your project, the following code will then take care of the rest:

string strBLOBFilePath = yourImageFilePath;
FileStream fsBLOBFile = new FileStream(strBLOBFilePath, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];

fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
fsBLOBFile.Close();