I'm using a list of InteropBitmap in order to display a set of image frames within Image control which is customized with a datatemplate.
What I'm lookin for is to export set of images in a single image, however what I get is a bad/partial image with wrong colors.
The following is the code snippet I'm using to convert set of InteropBitmap in a single image:
var firstInterop = this.InteropBitmapList[0]; // Get info from first frame, all other one are the same format.
int width = firstInterop .PixelWidth;
int height = firstInterop.PixelHeight;
int bpp = firstInterop Format.BitsPerPixel;
int stride = width * (bpp / 8);
int count = this.InteropBitmapList.Count;
byte[] buffer = new byte[stride * height * count];
for (int i = 0; i < count; i++)
{
var wb = this.InteropBitmapList[i];
wb.CopyPixels(buffer, stride, width * height * i);
}
Finally, I use buffer array to achieve my jpeg image through GDI+ or else wpf instruments. Unfortunately, both the way doesn't work as I expected.
Is there something to wrong in my code?
@@EDIT Well, thanks to Clemens answers, now I'm able to obtain a correct image, except only for its color (all colors are altered). The issue is true only when I try to create an Image through GDI+, instead, if I use something of WPF susch as JpegBitmapEncoder all works fine.
The following code snippet allow me to achieve the right image:
byte[] buffer = MyFunc.GetBuffer();
// ...
var bitmap = System.Windows.Media.Imaging.BitmapSource.Create(width, height, 300, 300,
System.Windows.Media.PixelFormats.Rgb24, null, buffer, stride);
System.IO.FileStream stream = new System.IO.FileStream("example.jpg", System.IO.FileMode.Create);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
Instead, the following code return me an image with wrong colors (the red become blue and so on)
byte[] buffer = MyFunc.GetBuffer();
// ...
IntPtr unmanagedPointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(buffer.Length);
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
System.Drawing.Imaging.PixelFormat format = System.Drawing.Imaging.PixelFormat.Format24bppRgb (the equivalent of WPF format..)
System.Drawing.Image myImg = new System.Drawing.Bitmap(Width, Height, stride, format, unmanagedPointer);
myImg.Save("example.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
I haven't idea why it doesn't work when I use System.Drawing classes.