| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Drawing; |
| 4 | using System.IO; |
| 5 | using System.Linq; |
| 6 | using System.Text; |
| 7 | using System.Threading.Tasks; |
| 8 | using System.Windows; |
| 9 | using System.Windows.Interop; |
| 10 | using System.Windows.Media; |
| 11 | using System.Windows.Media.Imaging; |
| 12 | using System.Windows.Resources; |
| 13 | |
| 14 | namespace Core.Librarys.Image |
| 15 | { |
| 16 | public class Imager |
| 17 | { |
| 18 | public static BitmapImage Load(string filePath, string defaultPath = "pack://application:,,,/Tai;component/Resources/Icons/defaultIcon.png") |
| 19 | { |
| 20 | try |
| 21 | { |
| 22 | if (string.IsNullOrEmpty(filePath)) |
| 23 | { |
| 24 | throw new ArgumentNullException(nameof(filePath)); |
| 25 | } |
| 26 | |
| 27 | var bitmap = new BitmapImage(); |
| 28 | bitmap.BeginInit(); |
| 29 | if (filePath.IndexOf("pack://") != -1) |
| 30 | { |
| 31 | StreamResourceInfo info = Application.GetResourceStream(new Uri(filePath, UriKind.RelativeOrAbsolute)); |
| 32 | using (var st = info.Stream) |
| 33 | { |
| 34 | bitmap.StreamSource = st; |
| 35 | bitmap.EndInit(); |
| 36 | bitmap.Freeze(); |
| 37 | } |
| 38 | } |
| 39 | else |
| 40 | { |
| 41 | if (filePath.IndexOf(":") == -1) |
| 42 | { |
| 43 | |
| 44 | filePath = Path.Combine(FileHelper.GetRootDirectory(), filePath); |
| 45 | } |
| 46 | |
| 47 | if (!File.Exists(filePath)) |
| 48 | { |
| 49 | throw new FileNotFoundException(filePath); |
| 50 | } |
| 51 | byte[] imageData; |
| 52 | using (var fileStream = new FileStream(@filePath, FileMode.Open, FileAccess.Read)) |
| 53 | |
| 54 | using (var binaryReader = new BinaryReader(fileStream)) |
| 55 | { |
| 56 | imageData = binaryReader.ReadBytes((int)fileStream.Length); |
| 57 | bitmap.StreamSource = new MemoryStream(imageData); |
| 58 | bitmap.EndInit(); |
| 59 | bitmap.Freeze(); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | return bitmap; |
| 64 | } |
| 65 | catch (Exception ec) |
| 66 | { |
| 67 | |
| 68 | |
| 69 | var bitmap = new BitmapImage(); |
| 70 | bitmap.BeginInit(); |
| 71 | |
| 72 | StreamResourceInfo info = Application.GetResourceStream(new Uri(defaultPath, UriKind.RelativeOrAbsolute)); |
| 73 | using (var st = info.Stream) |
| 74 | { |
| 75 | bitmap.StreamSource = st; |
| 76 | bitmap.EndInit(); |
| 77 | bitmap.Freeze(); |
| 78 | } |
| 79 | |
| 80 | Logger.Error("无法读取图片:" + filePath + "。" + ec.Message); |
| 81 | |
| 82 | return bitmap; |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |