Here is what I am using now. Some of the other methods I tried were not optimal because they changed the pixel bit depth (24-bit or 32-bit) or ignored the image resolution (dpi).
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into // Bitmap objects. This is static and only gets instantiated once. private static readonly ImageConverter _imageConverter = new ImageConverter();
Image to byte array:
Array byte for image:
/// <summary> /// Method that uses the ImageConverter object in .Net Framework to convert a byte array, /// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be /// used as an Image object. /// </summary> /// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param> /// <returns>Bitmap object if it works, else exception is thrown</returns> public static Bitmap GetImageFromByteArray(byte[] byteArray) { Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray); if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution || bm.VerticalResolution != (int)bm.VerticalResolution)) { // Correct a strange glitch that has been observed in the test program when converting // from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts" // slightly away from the nominal integer value bm.SetResolution((int)(bm.HorizontalResolution + 0.5f), (int)(bm.VerticalResolution + 0.5f)); } return bm; }
Edit: To retrieve an image from a jpg or png file, you must read the file into an array of bytes using File.ReadAllBytes ():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
This avoids Bitmap-related issues that want its source stream to be open, and some suggested workarounds for this issue that lock the source file.
RenniePet May 15 '13 at 23:11 2013-05-15 23:11
source share