【问题标题】:How to convert from type Image to type BitmapImage?如何从 Image 类型转换为 BitmapImage 类型?
【发布时间】:2011-08-12 13:54:24
【问题描述】:

有人知道如何从图像创建 BitmapImage 吗?这是我正在使用的代码:

MemoryStream memStream = new MemoryStream(bytes);
Image img = Image.FromStream(memStream);

现在我可以访问内存中的这张图片了。问题是我需要将其转换为 BitmapImage 类型,以便在我的解决方案中使用它。

注意:我需要将其转换为类型 BitmapImage 而不是类型 Bitmap。我无法弄清楚,因为 BitmapImage 类型接受了 Uri 作为它的构造函数。

【问题讨论】:

    标签: c# .net image image-processing


    【解决方案1】:
    Bitmap      img   = (Bitmap) Image.FromStream(memStream);
    BitmapImage bmImg = new BitmapImage();
    
    using (MemoryStream memStream2 = new MemoryStream()) 
    {
       img.Save(memStream2, System.Drawing.Imaging.ImageFormat.Png);
       memStream2.Position = 0;
    
       bmImg.BeginInit();
       bmImg.CacheOption = BitmapCacheOption.OnLoad;
       bmImg.UriSource = null;
       bmImg.StreamSource = memStream2;
       bmImg.EndInit();
    }
    

    【讨论】:

    • 您的代码也可以完美运行。出于某种原因,尽管我运行的一半图像是正常的,而另一半是负面的,就像我运行 Bala 的代码时一样。关于为什么会发生这种情况的任何想法?
    • 这很酷。我会看看它是否在我的代码中。同样像 25 个图像中有 3 个没有显示,但它们的一些属性仍然显示,如高度和宽度。这是内存问题吗?
    • 听起来不一定是内存问题。
    【解决方案2】:

    您确定需要 BitmapImage,而不是 BitmapSource? BitmapImage 是 BitmapSource 的子类,专门用于在 XAML 中创建源(来自 URI)。还有许多其他 BitmapSource 选择——其他选择之一可能会更好。

    例如,WriteableBitmap

    http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx

    你可以制作一个你想要的大小,然后将像素复制到它上面。

    【讨论】:

      【解决方案3】:

      来自this post

      public BitmapImage ImageFromBuffer(Byte[] bytes)
      {
          MemoryStream stream = new MemoryStream(bytes);
          BitmapImage image = new BitmapImage();
          image.BeginInit();
          image.StreamSource = stream;
          image.EndInit();
          return image;
      }
      

      【讨论】:

      • 您的代码运行良好。出于某种原因,尽管我浏览过的图像中有一半是正常的,而另一半是负面的。有什么想法吗?
      • @loyalpenguin 抱歉,我不知道为什么一半的图像结果是负面的。
      猜你喜欢
      • 2012-08-28
      • 2019-07-15
      • 1970-01-01
      • 2012-11-18
      • 2014-06-19
      • 2013-06-18
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多