ImageUtil.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. using GeekDesk.Constant;
  2. using System;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Text.RegularExpressions;
  7. using System.Windows.Media;
  8. using System.Windows.Media.Imaging;
  9. namespace GeekDesk.Util
  10. {
  11. class ImageUtil
  12. {
  13. private static readonly string SYSTEM_ITEM = "::{.*}";
  14. /// <summary>
  15. /// 图片数组转 BitmapImage
  16. /// </summary>
  17. /// <param name="array"></param>
  18. /// <returns></returns>
  19. public static BitmapImage ByteArrToImage(byte[] array)
  20. {
  21. if (array == null) return null;
  22. using (var ms = new System.IO.MemoryStream(array))
  23. {
  24. BitmapImage image = new BitmapImage();
  25. image.BeginInit();
  26. image.CacheOption = BitmapCacheOption.OnLoad; // here
  27. RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.LowQuality);
  28. image.StreamSource = ms;
  29. image.EndInit();
  30. return image;
  31. }
  32. }
  33. /// <summary>
  34. /// BitmapImage 转数组
  35. /// </summary>
  36. /// <param name="bi"></param>
  37. /// <returns></returns>
  38. public static byte[] BitmapImageToByte(BitmapImage bi)
  39. {
  40. if (bi == null) return null;
  41. using (MemoryStream memStream = new MemoryStream())
  42. {
  43. PngBitmapEncoder encoder = new PngBitmapEncoder();
  44. encoder.Frames.Add(BitmapFrame.Create(bi));
  45. encoder.Save(memStream);
  46. return memStream.GetBuffer();
  47. }
  48. }
  49. /// <summary>
  50. /// byte[]转换成Image
  51. /// </summary>
  52. /// <param name="byteArrayIn">二进制图片流</param>
  53. /// <returns>Image</returns>
  54. public static Image ByteArrayToImage(byte[] byteArrayIn)
  55. {
  56. if (byteArrayIn == null)
  57. return null;
  58. using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn))
  59. {
  60. System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
  61. ms.Flush();
  62. return returnImage;
  63. }
  64. }
  65. /// <summary>
  66. /// 图片base64 转 BitmapImage
  67. /// </summary>
  68. /// <param name="base64"></param>
  69. /// <returns></returns>
  70. public static BitmapImage Base64ToBitmapImage(string base64)
  71. {
  72. byte[] byteBuffer = Convert.FromBase64String(base64);
  73. return ByteArrToImage(byteBuffer);
  74. }
  75. /// <summary>
  76. /// 获取文件 icon
  77. /// </summary>
  78. /// <param name="filePath">文件路径</param>
  79. /// <returns></returns>
  80. public static BitmapImage GetBitmapIconByPath(string filePath)
  81. {
  82. if (filePath.Contains("%windir%"))
  83. {
  84. filePath = filePath.Replace("%windir%", System.Environment.GetEnvironmentVariable("windir"));
  85. }
  86. if (File.Exists(filePath) || IsSystemItem(filePath))
  87. {
  88. if (IsImage(filePath))
  89. {
  90. //图片
  91. return GetThumbnailByFile(filePath, 256, 256);
  92. }
  93. else
  94. { //其它文件
  95. return FileIcon.GetBitmapImage(filePath);
  96. }
  97. }
  98. else if (Directory.Exists(filePath))
  99. {
  100. if ((filePath.IndexOf("\\") == filePath.LastIndexOf("\\")) && filePath.IndexOf("\\") == filePath.Length - 1)
  101. {
  102. //磁盘
  103. return ImageUtil.Base64ToBitmapImage(Constants.DEFAULT_DISK_IMAGE_BASE64);
  104. }
  105. else
  106. {
  107. //文件夹
  108. return ImageUtil.Base64ToBitmapImage(Constants.DEFAULT_DIR_IMAGE_BASE64);
  109. }
  110. }
  111. return null;
  112. }
  113. public static BitmapImage GetBitmapIconByUnknownPath(string path)
  114. {
  115. //string base64 = ImageUtil.FileImageToBase64(path, System.Drawing.Imaging.ImageFormat.Png);
  116. string ext = "";
  117. if (!ImageUtil.IsSystemItem(path))
  118. {
  119. ext = System.IO.Path.GetExtension(path).ToLower();
  120. }
  121. string iconPath = null;
  122. if (".lnk".Equals(ext))
  123. {
  124. string targetPath = FileUtil.GetTargetPathByLnk(path);
  125. iconPath = FileUtil.GetIconPathByLnk(path);
  126. if (targetPath != null)
  127. {
  128. path = targetPath;
  129. }
  130. }
  131. if (StringUtil.IsEmpty(iconPath))
  132. {
  133. iconPath = path;
  134. }
  135. return ImageUtil.GetBitmapIconByPath(iconPath);
  136. }
  137. /// <summary>
  138. ///
  139. /// </summary>
  140. /// <param name="lcFilename">需要改变大小的图片位置</param>
  141. /// <param name="lnWidth">缩略图的宽度</param>
  142. /// <param name="lnHeight">缩略图的高度</param>
  143. /// <returns></returns>
  144. //public static BitmapImage GetThumbnail(string lcFilename, int lnWidth, int lnHeight)
  145. //{
  146. // Bitmap bmpOut = null;
  147. // try
  148. // {
  149. // Bitmap loBMP = new Bitmap(lcFilename);
  150. // ImageFormat loFormat = loBMP.RawFormat;
  151. // decimal lnRatio;
  152. // int lnNewWidth = 0;
  153. // int lnNewHeight = 0;
  154. // //如果图像小于缩略图直接返回原图,因为upfront
  155. // if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
  156. // return BitmapToBitmapImage(loBMP);
  157. // if (loBMP.Width > loBMP.Height)
  158. // {
  159. // lnRatio = (decimal)lnWidth / loBMP.Width;
  160. // lnNewWidth = lnWidth;
  161. // decimal lnTemp = loBMP.Height * lnRatio;
  162. // lnNewHeight = (int)lnTemp;
  163. // }
  164. // else
  165. // {
  166. // lnRatio = (decimal)lnHeight / loBMP.Height;
  167. // lnNewHeight = lnHeight;
  168. // decimal lnTemp = loBMP.Width * lnRatio;
  169. // lnNewWidth = (int)lnTemp;
  170. // }
  171. // bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
  172. // Graphics g = Graphics.FromImage(bmpOut);
  173. // g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  174. // g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
  175. // g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
  176. // loBMP.Dispose();
  177. // }
  178. // catch (Exception e)
  179. // {
  180. // return Base64ToBitmapImage(Constants.DEFAULT_IMG_IMAGE_BASE64);
  181. // }
  182. // return BitmapToBitmapImage(bmpOut);
  183. //}
  184. public static BitmapImage GetThumbnailByFile(string filePath, int tWidth, int tHeight)
  185. {
  186. try
  187. {
  188. FileInfo file = new FileInfo(filePath);
  189. if (file.Exists && file.Length > 0
  190. && !System.IO.Path.GetExtension(filePath).Contains("psd"))
  191. {
  192. Image img = Image.FromFile(filePath);
  193. if (img.Width <= tWidth && img.Height <= tHeight)
  194. {
  195. return GetBitmapImageByFile(filePath);
  196. }
  197. else
  198. {
  199. Bitmap loBMP = new Bitmap(filePath);
  200. ImageFormat loFormat = loBMP.RawFormat;
  201. decimal lnRatio;
  202. int lnNewWidth;
  203. int lnNewHeight;
  204. if (loBMP.Width > loBMP.Height)
  205. {
  206. lnRatio = (decimal)tWidth / loBMP.Width;
  207. lnNewWidth = tWidth;
  208. decimal lnTemp = loBMP.Height * lnRatio;
  209. lnNewHeight = (int)lnTemp;
  210. }
  211. else
  212. {
  213. lnRatio = (decimal)tHeight / loBMP.Height;
  214. lnNewHeight = tHeight;
  215. decimal lnTemp = loBMP.Width * lnRatio;
  216. lnNewWidth = (int)lnTemp;
  217. }
  218. Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
  219. Graphics g = Graphics.FromImage(bmpOut);
  220. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  221. g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
  222. g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
  223. loBMP.Dispose();
  224. string tempPath = Constants.APP_DIR + "\\temp";
  225. if (File.Exists(tempPath))
  226. {
  227. File.Delete(tempPath);
  228. }
  229. bmpOut.Save(tempPath, loFormat);
  230. BitmapImage bm = GetBitmapImageByFile(tempPath);
  231. File.Delete(tempPath);
  232. return bm;
  233. }
  234. } else
  235. {
  236. return Base64ToBitmapImage(Constants.DEFAULT_IMG_IMAGE_BASE64);
  237. }
  238. }
  239. catch (Exception e)
  240. {
  241. LogUtil.WriteErrorLog(e, "获取文件缩略图失败!filePath=" + filePath);
  242. return Base64ToBitmapImage(Constants.DEFAULT_IMG_IMAGE_BASE64);
  243. }
  244. }
  245. public static BitmapImage GetBitmapImageByFile(string filePath)
  246. {
  247. BitmapImage bmImg = new BitmapImage();
  248. bmImg.BeginInit();
  249. bmImg.CacheOption = BitmapCacheOption.OnLoad;
  250. RenderOptions.SetBitmapScalingMode(bmImg, BitmapScalingMode.LowQuality);
  251. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  252. {
  253. bmImg.StreamSource = fs;
  254. bmImg.EndInit();
  255. }
  256. return bmImg;
  257. }
  258. public static BitmapImage MemoryStremToBitMapImage(MemoryStream ms)
  259. {
  260. BitmapImage bi = new BitmapImage();
  261. bi.BeginInit();
  262. bi.StreamSource = ms;
  263. bi.CacheOption = BitmapCacheOption.OnLoad;
  264. bi.EndInit();
  265. bi.Freeze();
  266. return bi;
  267. }
  268. /// <summary>
  269. /// Bitmap to BitmapImage
  270. /// </summary>
  271. /// <param name="bitmap"></param>
  272. /// <returns></returns>
  273. public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
  274. {
  275. return BitmapToBitmapImage(bitmap, null);
  276. }
  277. public static BitmapImage BitmapToBitmapImage(Image bitmap, ImageFormat format)
  278. {
  279. BitmapImage bitmapImage = new BitmapImage();
  280. using (MemoryStream ms = new MemoryStream())
  281. {
  282. if (format == null)
  283. {
  284. bitmap.Save(ms, bitmap.RawFormat);
  285. }
  286. else
  287. {
  288. bitmap.Save(ms, format);
  289. }
  290. bitmapImage.BeginInit();
  291. bitmapImage.StreamSource = ms;
  292. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  293. bitmapImage.EndInit();
  294. bitmapImage.Freeze();
  295. }
  296. return bitmapImage;
  297. }
  298. [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  299. public static extern bool DeleteObject(IntPtr hObject);
  300. public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
  301. {
  302. MemoryStream ms = new MemoryStream();
  303. bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  304. BitmapImage bit3 = new BitmapImage();
  305. bit3.BeginInit();
  306. bit3.StreamSource = ms;
  307. bit3.EndInit();
  308. return bit3;
  309. }
  310. /// <summary>
  311. /// 图片文件转base64
  312. /// </summary>
  313. /// <param name="Imagefilename"></param>
  314. /// <returns></returns>
  315. public static string FileImageToBase64(string Imagefilename, ImageFormat format)
  316. {
  317. try
  318. {
  319. Bitmap bmp = new Bitmap(Imagefilename);
  320. MemoryStream ms = new MemoryStream();
  321. bmp.Save(ms, format);
  322. byte[] arr = new byte[ms.Length];
  323. ms.Position = 0;
  324. ms.Read(arr, 0, (int)ms.Length);
  325. ms.Close();
  326. return Convert.ToBase64String(arr);
  327. }
  328. catch (Exception e)
  329. {
  330. LogUtil.WriteErrorLog(e, "图片文件转base64失败!Imagefilename=" + Imagefilename + ",ImageFormat=" + format);
  331. return null;
  332. }
  333. }
  334. /// <summary>
  335. /// 判断文件是否为图片
  336. /// </summary>
  337. /// <param name="path">文件路径</param>
  338. /// <returns></returns>
  339. public static bool IsImage(string path)
  340. {
  341. try
  342. {
  343. string ext = Path.GetExtension(path);
  344. if (!string.IsNullOrEmpty(ext))
  345. {
  346. string strExt = Path.GetExtension(path).Substring(1);
  347. string suffixs = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif";
  348. string[] suffixArr = suffixs.Split(',');
  349. foreach (string suffix in suffixArr)
  350. {
  351. if (suffix.Equals(strExt, StringComparison.InvariantCultureIgnoreCase))
  352. {
  353. return true;
  354. }
  355. }
  356. }
  357. return false;
  358. }
  359. catch (Exception)
  360. {
  361. return false;
  362. }
  363. }
  364. /// <summary>
  365. /// 判断是否为系统项
  366. /// </summary>
  367. /// <returns></returns>
  368. public static bool IsSystemItem(string path)
  369. {
  370. return Regex.IsMatch(path, SYSTEM_ITEM);
  371. }
  372. }
  373. }