ImageUtil.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. Image img = Image.FromFile(filePath);
  189. if (img.Width <= tWidth && img.Height <= tHeight)
  190. {
  191. return GetBitmapImageByFile(filePath);
  192. }
  193. else
  194. {
  195. Bitmap loBMP = new Bitmap(filePath);
  196. ImageFormat loFormat = loBMP.RawFormat;
  197. decimal lnRatio;
  198. int lnNewWidth;
  199. int lnNewHeight;
  200. if (loBMP.Width > loBMP.Height)
  201. {
  202. lnRatio = (decimal)tWidth / loBMP.Width;
  203. lnNewWidth = tWidth;
  204. decimal lnTemp = loBMP.Height * lnRatio;
  205. lnNewHeight = (int)lnTemp;
  206. }
  207. else
  208. {
  209. lnRatio = (decimal)tHeight / loBMP.Height;
  210. lnNewHeight = tHeight;
  211. decimal lnTemp = loBMP.Width * lnRatio;
  212. lnNewWidth = (int)lnTemp;
  213. }
  214. Bitmap bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
  215. Graphics g = Graphics.FromImage(bmpOut);
  216. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  217. g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
  218. g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
  219. loBMP.Dispose();
  220. string tempPath = Constants.APP_DIR + "\\temp";
  221. if (File.Exists(tempPath))
  222. {
  223. File.Delete(tempPath);
  224. }
  225. bmpOut.Save(tempPath, loFormat);
  226. BitmapImage bm = GetBitmapImageByFile(tempPath);
  227. File.Delete(tempPath);
  228. return bm;
  229. }
  230. }
  231. catch (Exception e)
  232. {
  233. LogUtil.WriteErrorLog(e, "获取文件缩略图失败!filePath=" + filePath);
  234. return Base64ToBitmapImage(Constants.DEFAULT_IMG_IMAGE_BASE64);
  235. }
  236. }
  237. public static BitmapImage GetBitmapImageByFile(string filePath)
  238. {
  239. BitmapImage bmImg = new BitmapImage();
  240. bmImg.BeginInit();
  241. bmImg.CacheOption = BitmapCacheOption.OnLoad;
  242. RenderOptions.SetBitmapScalingMode(bmImg, BitmapScalingMode.LowQuality);
  243. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  244. {
  245. bmImg.StreamSource = fs;
  246. bmImg.EndInit();
  247. }
  248. return bmImg;
  249. }
  250. public static BitmapImage MemoryStremToBitMapImage(MemoryStream ms)
  251. {
  252. BitmapImage bi = new BitmapImage();
  253. bi.BeginInit();
  254. bi.StreamSource = ms;
  255. bi.CacheOption = BitmapCacheOption.OnLoad;
  256. bi.EndInit();
  257. bi.Freeze();
  258. return bi;
  259. }
  260. /// <summary>
  261. /// Bitmap to BitmapImage
  262. /// </summary>
  263. /// <param name="bitmap"></param>
  264. /// <returns></returns>
  265. public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
  266. {
  267. return BitmapToBitmapImage(bitmap, null);
  268. }
  269. public static BitmapImage BitmapToBitmapImage(Image bitmap, ImageFormat format)
  270. {
  271. BitmapImage bitmapImage = new BitmapImage();
  272. using (MemoryStream ms = new MemoryStream())
  273. {
  274. if (format == null)
  275. {
  276. bitmap.Save(ms, bitmap.RawFormat);
  277. }
  278. else
  279. {
  280. bitmap.Save(ms, format);
  281. }
  282. bitmapImage.BeginInit();
  283. bitmapImage.StreamSource = ms;
  284. bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
  285. bitmapImage.EndInit();
  286. bitmapImage.Freeze();
  287. }
  288. return bitmapImage;
  289. }
  290. [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  291. public static extern bool DeleteObject(IntPtr hObject);
  292. public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
  293. {
  294. MemoryStream ms = new MemoryStream();
  295. bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  296. BitmapImage bit3 = new BitmapImage();
  297. bit3.BeginInit();
  298. bit3.StreamSource = ms;
  299. bit3.EndInit();
  300. return bit3;
  301. }
  302. /// <summary>
  303. /// 图片文件转base64
  304. /// </summary>
  305. /// <param name="Imagefilename"></param>
  306. /// <returns></returns>
  307. public static string FileImageToBase64(string Imagefilename, ImageFormat format)
  308. {
  309. try
  310. {
  311. Bitmap bmp = new Bitmap(Imagefilename);
  312. MemoryStream ms = new MemoryStream();
  313. bmp.Save(ms, format);
  314. byte[] arr = new byte[ms.Length];
  315. ms.Position = 0;
  316. ms.Read(arr, 0, (int)ms.Length);
  317. ms.Close();
  318. return Convert.ToBase64String(arr);
  319. }
  320. catch (Exception e)
  321. {
  322. LogUtil.WriteErrorLog(e, "图片文件转base64失败!Imagefilename=" + Imagefilename + ",ImageFormat=" + format);
  323. return null;
  324. }
  325. }
  326. /// <summary>
  327. /// 判断文件是否为图片
  328. /// </summary>
  329. /// <param name="path">文件路径</param>
  330. /// <returns></returns>
  331. public static bool IsImage(string path)
  332. {
  333. try
  334. {
  335. string strExt = Path.GetExtension(path).Substring(1);
  336. string suffixs = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif";
  337. string[] suffixArr = suffixs.Split(',');
  338. foreach (string suffix in suffixArr)
  339. {
  340. if (suffix.Equals(strExt, StringComparison.InvariantCultureIgnoreCase))
  341. {
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. catch (Exception)
  348. {
  349. return false;
  350. }
  351. }
  352. /// <summary>
  353. /// 判断是否为系统项
  354. /// </summary>
  355. /// <returns></returns>
  356. public static bool IsSystemItem(string path)
  357. {
  358. return Regex.IsMatch(path, SYSTEM_ITEM);
  359. }
  360. }
  361. }