ImageUtil.cs 13 KB

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