I am trying to save jpeg image from buffer array of RGBA.
I tried this code
byte[] buffer = new byte[m_FrameProps.ImgSize];
Marshal.Copy(m_BM.BackBuffer, buffer, 0, m_FrameProps.ImgSize); //m_BM is WriteableBitmap
using (MemoryStream imgStream = new MemoryStream(buffer))
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(imgStream))
{
image.Save(m_WorkingDir + "1", ImageFormat.Jpeg);
}
}
But I am getting run-time error: "An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Additional information: Parameter is not valid."
I tried also to create bitmap and then to use JpegBitmapEncoder
Bitmap bitmap;
using (var ms = new MemoryStream(buffer))
{
bitmap = new Bitmap(ms);
}
But I am getting the same error.
I guess it is because the alpha.
How should I do it? Do I need to loop the values and copy without alpha?
It is not possible to construct an image from an array of pixel data alone. At minimum pixel format information and image dimensions would also be required. This means any attempt to create a Bitmap directly from an ARGB array using streams will fail, the Image.FromStream()
and Bitmap()
methods both require that the stream contain some kind of header information to construct an image.
That said, given that you appear to know the dimensions and pixel format of the image you wish to save you can use the following method:
public void SaveAsJpeg(int width, int height, byte[] argbData, int sourceStride, string path)
{
using (Bitmap img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
{
BitmapData data = img.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, img.PixelFormat);
for (int y = 0; y < height; y++)
{
Marshal.Copy(argbData, sourceStride * y, data.Scan0 + data.Stride * y, width * 4);
}
img.UnlockBits(data);
img.Save(path, ImageFormat.Jpeg);
}
}