0

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();
double-beep
  • 5,031
  • 17
  • 33
  • 41
Markus
  • 3
  • 3
  • Throw away all the System.Drawing.Bitmap stuff and see the answer to the duplicate question for how to create a BitmapSource directly from an encoded bitmap frame in a byte array. You may also set DecodePixelWidth or DecodePixelHeight to reduce the size of the decoded BitmapImage. – Clemens Mar 28 '23 at 17:26
  • And several hundred large images in memory won't work. Just sum up four bytes per pixel of all the bitmaps. – Clemens Mar 28 '23 at 17:43

0 Answers0