2011-04-12 27 views
1

我正在寫一個小程序,我想處理一些不同的圖像類型 - 其中包括:「高清照片」又名「JPEG XR」。在WinForms應用程序中打開並顯示一張高清照片

我試過一個簡單的Image.FromFile()但我得到了OutOfMemoryException。我試圖尋找一些解決方案,但我發現的寶貴的一些結果讓我懷疑這可能只適用於WPF應用程序。這是真的?如果沒有,那麼我怎樣才能打開這樣的文件,所以我可以把它放在Picturebox

+0

我正在調查在我的Winforms應用程序中託管WPF控件的一種可能的解決方法。 – Kempeth 2011-04-13 06:27:29

回答

1

我找到了一個可接受的解決方法。我已經寫了一個小型的WPF控件庫來加載高清照片並返回一個System.Drawing.Bitmap。

這是一個thisthis的問題,我自己改進了一些。當我嘗試原始源代碼時,我遇到了圖片大小調整後圖像消失的問題。它可能只是指向圖像信息的一些數組。通過將圖像繪製到第二個安全位圖中,我設法擺脫了這種效果。

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; 
    } 
} 
+0

太棒了!很高興你找到你的解決方案。 – FreeAsInBeer 2011-04-13 12:43:04

相關問題