Bitmap.Save vs File.WriteAllBytes

2019-08-13 15:29发布

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.

enter image description here

2条回答
Animai°情兽
2楼-- · 2019-08-13 15:53

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 in imgBuffer as your source, and you will get a Bitmap object back that you can use.

查看更多
乱世女痞
3楼-- · 2019-08-13 16:14

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 the File.WriteAllBytes method it just directly saves hence there is no corruption

查看更多
登录 后发表回答