WPF内存中图像显示 [英] WPF In-Memory Image Display

查看:61
本文介绍了WPF内存中图像显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的列表视图构建项目模板,并且将其绑定到实体列表.我拥有的实体有一个我想显示的 System.Drawing.Image ,但是到目前为止,我仍然无法确定如何将其绑定到< Image> 块.

Im trying to build an Item Template for my list-view and im bound to a list of Entities. The entity I have has a System.Drawing.Image that I'd like to display, but so far I cannot for the life of me figure out how to bind it to the <Image> block.

我在互联网上可以找到的每个示例和文档都与通过 uri (即HDD或网站上的文件)访问的图像有关

Every example and documentation I can find on the internet pertains to Images accessible via an uri i.e. File on HDD or On Website

    <DataTemplate x:Key="LogoPreviewItem">
        <Border BorderBrush="Black" BorderThickness="1">
            <DockPanel Width="150" Height="100">
                <Image>
                    <Image.Source>
                        <!--
                            {Binding PreviewImage} is where the System.Drawing.Image
                            is in this context
                        -->
                    </Image.Source>
                </Image>
                <Label DockPanel.Dock="Bottom" Content="{Binding CustomerName}" />
            </DockPanel>
        </Border>
    </DataTemplate>

推荐答案

System.Drawing.Image是WinForms/GDI +对象,在WPF世界中确实不合适.纯WPF程序通常不会使用System.Drawing.Image,而是会使用BitmapSource.但是有时我们会把旧的东西卡住一会儿.

A System.Drawing.Image is a WinForms / GDI+ object and is really out of place in the WPF world. A pure WPF program will generally not use System.Drawing.Image but will use BitmapSource instead. However sometimes we are stuck with the old stuff for a while.

您可以将图像从旧技术转换为新技术,如下所示:

You can convert your image from the old technology into the new as follows:

var oldImage = ...;  // System.Drawing.Image

var oldBitmap =
  oldImage as System.Drawing.Bitmap ??
  new System.Drawing.Bitmap(oldImage);

var bitmapSource =
   System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
     oldBitmap.GetHbitmap(System.Drawing.Color.Transparent),
     IntPtr.Zero,
     new Int32Rect(0, 0, oldBitmap.Width, oldBitmap.Height),
     null);

现在您可以设置:

myImage.Source = bitmapSource;

这比其他地方介绍的MemoryStream方法要快得多,因为它从未将位图数据序列化为流.

This is much faster than the MemoryStream approach that you will find described elsewhere, since it never serializes the bitmap data to a stream.

这篇关于WPF内存中图像显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆