星火微课系统客户端
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ImageHelper.cs 14KB

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