星火微课系统客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImageHelper.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Configuration;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Text;
  7. using System.Windows;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Imaging;
  10. namespace Common.system
  11. {
  12. /// <summary>
  13. /// 图片帮助类
  14. /// 创建人:赵耀
  15. /// 创建时间:2018年11月1日
  16. /// </summary>
  17. public class ImageHelper
  18. {
  19. /// <summary>
  20. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  21. /// </summary>
  22. /// <param name="path">图片位置</param>
  23. /// <returns></returns>
  24. public static Bitmap ReadBitmapFile(string path)
  25. {
  26. try
  27. {
  28. if (File.Exists(path))
  29. {
  30. FileStream fs = File.OpenRead(path); //OpenRead
  31. int filelength = 0;
  32. filelength = (int)fs.Length; //获得文件长度
  33. Byte[] image = new Byte[filelength]; //建立一个字节数组
  34. fs.Read(image, 0, filelength); //按字节流读取
  35. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  36. fs.Close();
  37. Bitmap bit = new Bitmap(result);
  38. return bit;
  39. }
  40. else
  41. return null;
  42. }
  43. catch (Exception)
  44. {
  45. return null;
  46. }
  47. }
  48. /// <summary>
  49. /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
  50. /// </summary>
  51. /// <param name="path">图片位置</param>
  52. /// <returns></returns>
  53. public static Image ReadImageFile(string path)
  54. {
  55. try
  56. {
  57. if (File.Exists(path))
  58. {
  59. FileStream fs = File.OpenRead(path); //OpenRead
  60. int filelength = 0;
  61. filelength = (int)fs.Length; //获得文件长度
  62. Byte[] image = new Byte[filelength]; //建立一个字节数组
  63. fs.Read(image, 0, filelength); //按字节流读取
  64. System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
  65. fs.Close();
  66. return result;
  67. }
  68. else
  69. return null;
  70. }
  71. catch (Exception)
  72. {
  73. return null;
  74. }
  75. }
  76. #region 获取RGB
  77. private static Bitmap _Bitmap = null;
  78. private static StringBuilder sb = new StringBuilder();
  79. public static string GetRGB(int x, int y)
  80. {
  81. sb = new StringBuilder();
  82. try
  83. {
  84. System.Drawing.Color color = _Bitmap.GetPixel(x, y);
  85. sb.Append("RGB:(");
  86. sb.Append(color.R.ToString());
  87. sb.Append(",");
  88. sb.Append(color.G.ToString());
  89. sb.Append(",");
  90. sb.Append(color.B.ToString());
  91. sb.Append(")");
  92. }
  93. catch (Exception ex)
  94. {
  95. LogHelper.WriteErrLog("ImageHelper(GetRGB)" + ex.Message, ex);
  96. }
  97. return sb.ToString();
  98. }
  99. #endregion 获取RGB
  100. #region 截图统一方法
  101. /// <summary>
  102. /// 截图通用方法 创建人:赵耀 创建时间:2020年8月11日
  103. /// </summary>
  104. /// <param name="ScreenSize">截图的区域,设置new Rectangle(0, 0, 0, 0)为截全屏</param>
  105. /// <param name="ImageSavePath">图片存储路径,为空或null则保存到临时文件夹</param>
  106. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  107. /// <returns></returns>
  108. public static BitmapImage GetScreenshot(Rectangle ScreenSize, string ImageSavePath, long level = -1)
  109. {
  110. try
  111. {
  112. System.Drawing.Size bounds = PrimaryScreen.DESKTOP;
  113. if (string.IsNullOrEmpty(ImageSavePath))
  114. {
  115. ImageSavePath = GetTempImagePath();//如果为空则指定临时存储路径
  116. }
  117. double scaleWidth = (bounds.Width * 1.0) / SystemParameters.PrimaryScreenWidth;
  118. double scaleHeight = (bounds.Height * 1.0) / SystemParameters.PrimaryScreenHeight;
  119. int width = bounds.Width;
  120. int height = bounds.Height;
  121. if (ScreenSize.Size != new System.Drawing.Size(0, 0))
  122. {
  123. width = (int)(ScreenSize.Size.Width * scaleWidth);
  124. height = (int)(ScreenSize.Size.Height * scaleHeight);
  125. }
  126. int l = (int)(ScreenSize.X * scaleWidth);
  127. int t = (int)(ScreenSize.Y * scaleHeight);
  128. if (_Bitmap != null)
  129. {
  130. _Bitmap.Dispose();
  131. }
  132. _Bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  133. using (Graphics g = Graphics.FromImage(_Bitmap))
  134. {
  135. g.CopyFromScreen(l, t, 0, 0, _Bitmap.Size, CopyPixelOperation.SourceCopy);
  136. Compress(_Bitmap, ImageSavePath, level);
  137. }
  138. Uri uri = new Uri(ImageSavePath, UriKind.Absolute);
  139. BitmapImage bimg = new BitmapImage(uri);
  140. GC.Collect();
  141. return bimg;
  142. }
  143. catch (Exception ex)
  144. {
  145. LogHelper.WriteErrLog("【截图】(GetBitmapSource)截图失败," + ex.Message, ex);
  146. return null;
  147. }
  148. }
  149. /// <summary>
  150. /// 获取临时图片保存位置
  151. /// </summary>
  152. /// <returns></returns>
  153. public static string GetTempImagePath()
  154. {
  155. string TempPath=FileToolsCommon.GetFileAbsolutePath("/temp/Screenshot/");
  156. FileToolsCommon.CreateDirectory(TempPath);
  157. return TempPath;
  158. }
  159. #endregion 截图统一方法
  160. #region 图片压缩
  161. /// <summary>
  162. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  163. /// </summary>
  164. /// <param name="srcBitMap">传入的Bitmap对象</param>
  165. /// <param name="destFile">压缩后的图片保存路径</param>
  166. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  167. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  168. {
  169. if (level <= -1)
  170. {
  171. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  172. level = ImageCompressionLevel;
  173. }
  174. Stream s = new FileStream(destFile, FileMode.Create);
  175. Compress(srcBitMap, s, level);
  176. s.Close();
  177. }
  178. /// <summary>
  179. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  180. /// </summary>
  181. /// <param name="srcBitmap">传入的Bitmap对象</param>
  182. /// <param name="destStream">压缩后的Stream对象</param>
  183. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  184. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  185. {
  186. ImageCodecInfo myImageCodecInfo;
  187. System.Drawing.Imaging.Encoder myEncoder;
  188. EncoderParameter myEncoderParameter;
  189. EncoderParameters myEncoderParameters;
  190. //获取表示jpeg编解码器的imagecodecinfo对象
  191. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  192. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  193. myEncoderParameters = new EncoderParameters(1);
  194. myEncoderParameter = new EncoderParameter(myEncoder, level);
  195. myEncoderParameters.Param[0] = myEncoderParameter;
  196. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  197. }
  198. /// <summary>
  199. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  200. /// </summary>
  201. /// <param name="mimeType"></param>
  202. /// <returns></returns>
  203. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  204. {
  205. int j;
  206. ImageCodecInfo[] encoders;
  207. encoders = ImageCodecInfo.GetImageEncoders();
  208. for (j = 0; j < encoders.Length; ++j)
  209. {
  210. if (encoders[j].MimeType == mimeType)
  211. {
  212. return encoders[j];
  213. }
  214. }
  215. return null;
  216. }
  217. /// <summary>
  218. /// 压缩图片 -测试方法 待完善 暂无用
  219. /// </summary>
  220. /// <param name="_bitmap">原图片</param>
  221. /// <param name="dFile">压缩后保存图片地址</param>
  222. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  223. /// <param name="size">压缩后图片的最大大小</param>
  224. /// <param name="sfsc">是否是第一次调用</param>
  225. /// <returns></returns>
  226. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  227. {
  228. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  229. //FileInfo firstFileInfo = new FileInfo(sFile);
  230. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  231. //{
  232. // firstFileInfo.CopyTo(dFile);
  233. // return true;
  234. //}
  235. //Image iSource = Image.FromFile(sFile);
  236. Image iSource = _bitmap;
  237. ImageFormat tFormat = iSource.RawFormat;
  238. int dHeight = iSource.Height / 2;
  239. int dWidth = iSource.Width / 2;
  240. int sW, sH;
  241. //按比例缩放
  242. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  243. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  244. {
  245. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  246. {
  247. sW = dWidth;
  248. sH = (dWidth * tem_size.Height) / tem_size.Width;
  249. }
  250. else
  251. {
  252. sH = dHeight;
  253. sW = (tem_size.Width * dHeight) / tem_size.Height;
  254. }
  255. }
  256. else
  257. {
  258. sW = tem_size.Width;
  259. sH = tem_size.Height;
  260. }
  261. Bitmap ob = new Bitmap(dWidth, dHeight);
  262. Graphics g = Graphics.FromImage(ob);
  263. g.Clear(System.Drawing.Color.WhiteSmoke);
  264. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  265. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  266. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  267. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  268. g.Dispose();
  269. //以下代码为保存图片时,设置压缩质量
  270. EncoderParameters ep = new EncoderParameters();
  271. long[] qy = new long[1];
  272. qy[0] = flag;//设置压缩的比例1-100
  273. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  274. ep.Param[0] = eParam;
  275. try
  276. {
  277. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  278. ImageCodecInfo jpegICIinfo = null;
  279. for (int x = 0; x < arrayICI.Length; x++)
  280. {
  281. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  282. {
  283. jpegICIinfo = arrayICI[x];
  284. break;
  285. }
  286. }
  287. if (jpegICIinfo != null)
  288. {
  289. if (flag > 0)
  290. {
  291. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  292. FileInfo fi = new FileInfo(dFile);
  293. if (fi.Length > 1024 * size)
  294. {
  295. flag -= 10;
  296. CompressImage(_bitmap, dFile, flag, size);
  297. }
  298. }
  299. //ob.Save(dFile, jpegICIinfo, ep);
  300. //FileInfo fi = new FileInfo(dFile);
  301. //bool IsAgain = false;
  302. //if (fi.Length > 1024 * size)
  303. //{
  304. // fi.CopyTo(dFile + fi.Length);
  305. // fi.Delete();
  306. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  307. // CompressImage(newbitmap, dFile, flag, size);
  308. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  309. //}
  310. }
  311. else
  312. {
  313. ob.Save(dFile, tFormat);
  314. }
  315. return true;
  316. }
  317. catch
  318. {
  319. return false;
  320. }
  321. finally
  322. {
  323. iSource.Dispose();
  324. ob.Dispose();
  325. }
  326. }
  327. #endregion 图片压缩
  328. #region 截屏指定UI控件
  329. /// <summary>
  330. /// 保存图片
  331. /// </summary>
  332. /// <param name="ui">需要截图的UI控件</param>
  333. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  334. /// <param name="width">保存宽</param>
  335. /// <param name="height">保存高</param>
  336. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height)
  337. {
  338. try
  339. {
  340. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  341. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
  342. PixelFormats.Pbgra32);
  343. bmp.Render(ui);
  344. BitmapEncoder encoder = new PngBitmapEncoder();
  345. encoder.Frames.Add(BitmapFrame.Create(bmp));
  346. encoder.Save(fs);
  347. fs.Close();
  348. }
  349. catch (Exception ex)
  350. {
  351. LogHelper.WriteErrLog("【UI生成图片】(SaveUIToImage)" + ex.Message, ex);
  352. //Console.WriteLine(ex.Message);
  353. }
  354. }
  355. #endregion
  356. }
  357. }