Open and display HD Photo in WinForms

I am writing a small program where I would like to process several different types of images - among other things: "HD Photo", aka "JPEG XR".

I tried simple Image.FromFile()but get it OutOfMemoryException. I tried to find some solutions, but due to a few minor results, I found the suspicion that this could only work in a WPF application. It's true? If not, how can I open such a file so that I can put it in Picturebox?

+1
source share
1 answer

I found an acceptable workaround. I wrote a small WPF control library that loads HD photos and returns System.Drawing.Bitmap.

This is a combination of this and this question with a few of my own improvements. I tried the original source, I had a problem that the image disappeared when I resized the image. This is probably due to the fact that it simply points to some array for image information. By drawing the image in the second safe bitmap, I managed to get rid of this effect.

public class HdPhotoLoader
{
    public static System.Drawing.Bitmap BitmapFromUri(String uri)
    {
        return BitmapFromUri(new Uri(uri, UriKind.Relative));
    }

    public static System.Drawing.Bitmap BitmapFromUri(Uri uri)
    {
        Image img = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.UriSource = uri;
        src.CacheOption = BitmapCacheOption.OnLoad;
        src.EndInit();
        img.Source = src;

        return BitmapSourceToBitmap(src);
    }

    public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
    {
        System.Drawing.Bitmap temp = null;
        System.Drawing.Bitmap result;
        System.Drawing.Graphics g;
        int width = srs.PixelWidth;
        int height = srs.PixelHeight;
        int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);

        byte[] bits = new byte[height * stride];

        srs.CopyPixels(bits, stride, 0);

        unsafe
        {
            fixed (byte* pB = bits)
            {

                IntPtr ptr = new IntPtr(pB);

                temp = new System.Drawing.Bitmap(
                      width,
                      height,
                      stride,
                      System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                      ptr);
            }

        }

        // Copy the image back into a safe structure
        result = new System.Drawing.Bitmap(width, height);
        g = System.Drawing.Graphics.FromImage(result);

        g.DrawImage(temp, 0, 0);
        g.Dispose();

        return result;
    }
}
+1
source

Source: https://habr.com/ru/post/1716145/


All Articles