简体   繁体   English

如何从 Image 类型转换为 BitmapImage 类型?

[英]How to convert from type Image to type BitmapImage?

Does anyone know how to create a BitmapImage from an Image?有谁知道如何从图像创建位图图像? Here is the code that I'm working with:这是我正在使用的代码:

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

Now I have access to this image in memory.现在我可以访问内存中的这张图片。 The thing is I need to convert this to type BitmapImage in order to use it in my solution.问题是我需要将其转换为 BitmapImage 类型,以便在我的解决方案中使用它。

NOTE: I need to convert it to type BitmapImage not type Bitmap .注意:我需要将其转换为BitmapImage类型而不是Bitmap类型。 I haven't been able to figure it out because type BitmapImage takes in a Uri for it's constructor.我一直无法弄清楚,因为 BitmapImage 类型为它的构造函数接受了一个 Uri。

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();
}

From 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;
}

Are you sure you need BitmapImage, not BitmapSource?你确定你需要 BitmapImage,而不是 BitmapSource? BitmapImage is a subclass of BitmapSource specifically for making a source in XAML (from a URI). BitmapImage 是 BitmapSource 的子类,专门用于在 XAML(来自 URI)中制作源。 There are many other BitmapSource choices -- one of the other choices might be better.还有许多其他 BitmapSource 选择——其他选择之一可能更好。

For example, WriteableBitmap例如,可写位图

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

You can make one of the size you want, and then copy pixels over to it.您可以制作您想要的尺寸之一,然后将像素复制到它上面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM