【问题标题】:Open and display a HD Photo in WinForms application在 WinForms 应用程序中打开并显示高清照片
【发布时间】:2011-08-03 21:44:05
【问题描述】:

我正在编写一个小程序,我想在其中处理多种不同的图像类型 - 其中包括:“高清照片”又名“JPEG XR”。

我尝试了一个简单的Image.FromFile(),但我得到了一个OutOfMemoryException。我试图寻找一些解决方案,但我发现的宝贵的少数结果让我怀疑这可能只适用于 WPF 应用程序。这是真的?如果没有,那么如何打开这样的文件,以便将其放入Picturebox

【问题讨论】:

  • 我正在研究在我的 Winforms 应用中托管 WPF 控件的可能解决方法。

标签: .net winforms image


【解决方案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;
    }
}

【讨论】:

  • 太棒了!很高兴您找到了解决方案。
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多