在做项目的过程中遇到这样一个问题,下面提出一种解决方法,主要思想是图片的Copy,如还有其他方法,欢迎交流。
在前端图片控件绑定显示时,使用转换器进行转义绑定
(1)转换器:
public class ImgConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
using (BinaryReader loader = new BinaryReader(File.Open(value.ToString(), FileMode.Open)))
{
FileInfo fd = new FileInfo(value.ToString());
int Length = (int) fd.Length;
byte[] buf = new byte[Length];
buf = loader.ReadBytes((int) fd.Length);
loader.Dispose();
loader.Close(); //开始加载图像
BitmapImage bim = new BitmapImage();
bim.BeginInit();
bim.StreamSource = new MemoryStream(buf);
bim.EndInit();
GC.Collect();
return bim;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return parameter;
}
}
(2)在页面加载转换器资源
<converters:ImgConverter x:Key="ImgCnverter"/>
(3)图片控件绑定转换器
xaml代码:
<Image Width="120" Height="80" Source="{Binding ImageLocalPath,Converter={StaticResource ImgCnverter}}"/>
显示效果如下图: