ImageUtil.cs 13 KB

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