FileToImageSourceConvert.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Data;
  9. using System.Windows.Media.Imaging;
  10. namespace PDF_Master.DataConvert
  11. {
  12. /// <summary>
  13. /// 文件绝对路径 转ImageSource 转换器
  14. /// </summary>
  15. public class FileToImageSourceConvert : IValueConverter
  16. {
  17. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  18. {
  19. if(!string.IsNullOrEmpty((string)value)&&System.IO.File.Exists((string)value))
  20. {
  21. //采用数组的形式读取,避免因bitmap占用,导致图片无法引用的问题
  22. // Read byte[] from png file
  23. BinaryReader binReader = new BinaryReader(File.Open((string)value, FileMode.Open));
  24. FileInfo fileInfo = new FileInfo((string)value);
  25. byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
  26. binReader.Close();
  27. // Init bitmap
  28. BitmapImage bitmap = new BitmapImage();
  29. bitmap.BeginInit();
  30. bitmap.StreamSource = new MemoryStream(bytes);
  31. bitmap.EndInit();
  32. return bitmap;
  33. }
  34. return null;
  35. }
  36. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  37. {
  38. throw new NotImplementedException();
  39. }
  40. }
  41. }