WPF图像:运行时动态更改图像源

26

我有一个带标题的窗口。当用户从下拉列表中选择选项时,标题图像可能会更改。问题在于当图像加载时,它会变成模糊、拉伸和像素化。我正在使用的是PNG文件,在动态设置源之前它们看起来很好。

这是我用来更改图像源的代码:

string strUri2 = String.Format(@"pack://application:,,,/MyAssembly;component/resources/main titles/{0}", CurrenSelection.TitleImage);
Stream iconStream2 = App.GetResourceStream(new Uri(strUri2)).Stream;
imgTitle.Source = HelperFunctions.returnImage(iconStream2);

这里是辅助函数。

    public static BitmapImage returnImage(Stream iconStream)
    {
        Bitmap brush = new Bitmap(iconStream);
        System.Drawing.Image img = brush.GetThumbnailImage(brush.Height, brush.Width, null, System.IntPtr.Zero);
        var imgbrush = new BitmapImage();
        imgbrush.BeginInit();
        imgbrush.StreamSource = ConvertImageToMemoryStream(img);
        imgbrush.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        imgbrush.EndInit();
        var ib = new ImageBrush(imgbrush);
        return imgbrush;
    }

    public static MemoryStream ConvertImageToMemoryStream(System.Drawing.Image img)
    {
        var ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms;
    }

还有XAML

            <Image x:Name="imgTitle" HorizontalAlignment="Left" VerticalAlignment="Bottom" Grid.Column="1" Grid.Row="1" Stretch="None" d:IsLocked="False"/>

参考文献:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

有人有任何想法吗?发生了什么事?

6个回答

28

我能想到两件事情:

首先,尝试使用以下方式加载图像:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

也许问题出在WinForm的图像缩放上,如果图像被拉伸,请将图像控件上的Stretch设置为"Uniform"或"UniformToFill"。

第二种可能是图片没有对齐到像素网格,您可以在我的博客上阅读更多信息:http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx


10

嘿,这个有点丑陋,但只有一行:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

1
如果您的图像位于子文件夹中,请使用以下代码:ico.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/YourFolder/your_image.png")); - Junior Mayhé

4

以下是我成功使用的方法。 在资源中添加图片。

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

然后代码就像这样。
Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

“this”指的是Window对象。

3

对我来说,工作就是:

string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png"; image1.Source = new BitmapImage(new Uri(strUri2));

以上代码涉及 IT 技术。

在以下代码中,BlackPlayerPic 的类型为 Image。BitmapImage activeBlackPlayer = new BitmapImage(new Uri("C:\\png\\turn_black.png")); BlackPlayerPic.Source = activeBlackPlayer; - Pabitra Dash

3
Me.imgAddNew.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/SPMS;component/Images/Cancel__Red-64.png", UriKind.Relative))

2
尝试在图片上使用Stretch="UniformToFill"属性

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接