WPF中Image控件绑定数据源,解决图片被占用问题

WPF中Image控件的数据源如果设置为路径,或者后台通过Image.FromFile来绑定,该图片将被占用,如要进行图片压缩、删除等操作则会报图片被占用的错;所以可以从内存中加载图片进行绑定。

以下为MVVMLight模式,首先增加一个图片路径值转换的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class ImageConvert : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            string path = value.ToString();
            if (File.Exists(path))
            {
                BinaryReader binaryReader = new BinaryReader(File.Open(path, FileMode.Open));
                FileInfo fileInfo = new FileInfo(path);
                byte[] bytes = binaryReader.ReadBytes((int)fileInfo.Length);
                binaryReader.Close();
                Bitmap bmTemp = new Bitmap(new MemoryStream(bytes));
                Bitmap bmNew = new Bitmap(bmTemp.Width, bmTemp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                bmNew.SetResolution(96, 96);
                using (Graphics g = Graphics.FromImage(bmNew))
                {
                    g.Clear(System.Drawing.Color.Transparent);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(bmTemp, new Rectangle(0, 0, bmNew.Width, bmNew.Height), 0, 0, bmTemp.Width, bmTemp.Height, GraphicsUnit.Pixel);
                    g.Dispose();
                }
                BitmapImage bitmapImage = new BitmapImage();
                using (MemoryStream ms = new MemoryStream())
                {
                    bmNew.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
 
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = ms;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
 
                    ms.Dispose();
                }
                return bitmapImage;
            }
            else
            {
                return null;
            }
        }
        catch (Exception)
        {
            return null;
        }
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

  View中的关键代码如下:

1
2
3
4
5
6
7
8
9
<UserControl.Resources>
     <vc:ImageConvert x:Key="string2Img" />
 </UserControl.Resources>
 
<Grid>
    <Image
                Source="{Binding Path=ImagePath,Converter={StaticResource string2Img}}"
                Stretch="Fill" />
</Grid>

 最后,ViewModel中给ImagePath绑定值,ImagePath的值为图片的路径

posted @   微笑着微笑  阅读(696)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示