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

发布时间 2023-10-13 14:53:26作者: 微笑着微笑

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

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

 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中的关键代码如下:

 <UserControl.Resources>
     <vc:ImageConvert x:Key="string2Img" />
 </UserControl.Resources>

<Grid>
    <Image
                Source="{Binding Path=ImagePath,Converter={StaticResource string2Img}}"
                Stretch="Fill" />
</Grid>

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