跳到主要内容

github/tai

公开

Tai · Windows 软件与网站使用时长统计。上游 Planshit/Tai 的源码镜像,非灵栈原创;MIT 许可。来源:https://github.com/Planshit/Tai 。本次为手动同步,暂不提供安装包。

浏览文件

Imager.cs

86 行 · 2.8 KB历史下载
1using System;
2using System.Collections.Generic;
3using System.Drawing;
4using System.IO;
5using System.Linq;
6using System.Text;
7using System.Threading.Tasks;
8using System.Windows;
9using System.Windows.Interop;
10using System.Windows.Media;
11using System.Windows.Media.Imaging;
12using System.Windows.Resources;
13
14namespace 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}