I have built a UserControl
to display thumbnails for individual pages of various documents. I get the images via different libraries as byte[]
. I now need to convert this so that I can display it in an image control. So far I have first created a Drawing.Bitmap
from the array using a MemoryStream
and then converted that with GetHbitmap()
first to a IntPtr
and then to a BitmapSource
. For larger or very high resolution documents, after a few pages with IntPtr hBitmap = image.GetHbitmap()
; I first get a message "Not enough memory."
, then "General error in GDI+."
I have now tried various suggestions from the Internet to change the conversion. Last I tried to write the byte[]
into a WriteableBitmap
and use this for display. But so far I couldn't get it to work.
So now the general question: What is the best way to convert image data from a byte[]
into an image (BitmapSource, BitmapImage, WriteableBitmap
), so that the content can be updated quickly and without memory overflow even for several hundred pages. Does it make sense at all to do that in memory or should you save the image as a jpg
to disk first, for example?
Here is my code so far. In my real code preview is a property to which the source of the image control is bound.
System.Drawing.Bitmap image
using (MemoryStream imageStream = new MemoryStream(byteArray))
{
image = new System.Drawing.Bitmap(imageStream);
}
IntPtr hBitmap = image.GetHbitmap();
BitmapSource preview =
Imaging
.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero,
Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
preview.Freeze();
DeleteObject(hBitmap);
image.Dispose();