I have a byte array (imgBuffer) which contains the rgb values for a jpeg image. I would like to save this to a Bitmap. When I use System.IO.File.WriteAllBytes("fileImg.jpg", imgBuffer);
I am able see the image in my directory in its correct format. The image gets corrupted when I try to write the same byte array, imgBuffer, to a Bitmap object. (The image format is 24bpp, 320x240)
BitmapData data;
Bitmap myBitmap = new Bitmap(320, 240, PixelFormat.Format24bppRgb);
//convert bytes to a bitmap
data = myBitmap .LockBits(new Rectangle(Point.Empty, bitmapResized.Size), ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
Marshal.Copy(imgBuffer, 0, data.Scan0, imgBuffer.Length);
myBitmap .UnlockBits(data);
myBitmap .Save("bitmapImg.jpg");
What must I change so that bitmapImg is correctly outputted to my directory? I am currently getting the following corrupted image.
If you can save your
imgBuffer
byte array to disk and read it as a JPEG in an image viewer, then it is not the raw RGB values for the image.You can load a
Bitmap
from a stream and use the data inimgBuffer
as your source, and you will get aBitmap
object back that you can use.I believe the problem here is that the
Bitmap
code assumes the data is in the bitmap format. The Save method first converts that to jpg and then saves it out. In this case it is already in the jpg format hence converting jpg to jpg is corrupting the image. In theFile.WriteAllBytes
method it just directly saves hence there is no corruption