Reputation: 1948
I'm writing a small program where I would like to handle a number of different image types - among other things: "HD Photo" aka "JPEG XR".
I've tried a simple Image.FromFile()
but I get an OutOfMemoryException
. I've tried to search for some solutions but the precious few results I've found gave me the suspicion that this might only work in a WPF application. Is this true? If not then how can I open such a file so I can put it in a Picturebox
?
Upvotes: 1
Views: 770
Reputation: 1948
I've found an acceptable workaround. I've written a small WPF Controls Library that loads HD Photos and returns a System.Drawing.Bitmap.
It's a combination of this and this question with a bit of my own improvements thrown in. When I tried the original source I had the problem that the image vanished when I resized the picturebox. It probably has something to do with just pointing to some array for the image info. By drawing the image into a second safe Bitmap I managed to get rid of that 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;
}
}
Upvotes: 1