星火微课系统客户端
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 _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. //private static Bitmap _Bitmap = null;
  150. //public static string GetRGB(int x, int y)
  151. //{
  152. // StringBuilder sb = new StringBuilder();
  153. // try
  154. // {
  155. // Color color = _Bitmap.GetPixel(x, y);
  156. // sb.Append("RGB:(");
  157. // sb.Append(color.R.ToString());
  158. // sb.Append(",");
  159. // sb.Append(color.G.ToString());
  160. // sb.Append(",");
  161. // sb.Append(color.B.ToString());
  162. // sb.Append(")");
  163. // }
  164. // catch (Exception ex)
  165. // {
  166. // throw ex;
  167. // }
  168. // return sb.ToString();
  169. //}
  170. #endregion 截图统一方法
  171. #region 图片压缩
  172. /// <summary>
  173. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  174. /// </summary>
  175. /// <param name="srcBitMap">传入的Bitmap对象</param>
  176. /// <param name="destFile">压缩后的图片保存路径</param>
  177. /// <param name="level">压缩等级,-1为config配置的值,0到100,0 最差质量,100 最佳</param>
  178. public static void Compress(Bitmap srcBitMap, string destFile, long level)
  179. {
  180. if (level <= -1)
  181. {
  182. int ImageCompressionLevel = int.Parse(FileToolsCommon.GetConfigValue("ImageCompressionLevel"));
  183. level = ImageCompressionLevel;
  184. }
  185. Stream s = new FileStream(destFile, FileMode.Create);
  186. Compress(srcBitMap, s, level);
  187. s.Close();
  188. }
  189. /// <summary>
  190. /// 图片压缩(降低质量以减小文件的大小) 创建人:赵耀 创建时间:2020年8月11日
  191. /// </summary>
  192. /// <param name="srcBitmap">传入的Bitmap对象</param>
  193. /// <param name="destStream">压缩后的Stream对象</param>
  194. /// <param name="level">压缩等级,0到100,0 最差质量,100 最佳</param>
  195. public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
  196. {
  197. ImageCodecInfo myImageCodecInfo;
  198. System.Drawing.Imaging.Encoder myEncoder;
  199. EncoderParameter myEncoderParameter;
  200. EncoderParameters myEncoderParameters;
  201. //获取表示jpeg编解码器的imagecodecinfo对象
  202. myImageCodecInfo = GetEncoderInfo("image/jpeg");
  203. myEncoder = System.Drawing.Imaging.Encoder.Quality;
  204. myEncoderParameters = new EncoderParameters(1);
  205. myEncoderParameter = new EncoderParameter(myEncoder, level);
  206. myEncoderParameters.Param[0] = myEncoderParameter;
  207. srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
  208. }
  209. /// <summary>
  210. /// 获取解码器 创建人:赵耀 创建时间2020年8月11日
  211. /// </summary>
  212. /// <param name="mimeType"></param>
  213. /// <returns></returns>
  214. private static ImageCodecInfo GetEncoderInfo(string mimeType)
  215. {
  216. int j;
  217. ImageCodecInfo[] encoders;
  218. encoders = ImageCodecInfo.GetImageEncoders();
  219. for (j = 0; j < encoders.Length; ++j)
  220. {
  221. if (encoders[j].MimeType == mimeType)
  222. {
  223. return encoders[j];
  224. }
  225. }
  226. return null;
  227. }
  228. /// <summary>
  229. /// 压缩图片 -测试方法 待完善 暂无用
  230. /// </summary>
  231. /// <param name="_bitmap">原图片</param>
  232. /// <param name="dFile">压缩后保存图片地址</param>
  233. /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
  234. /// <param name="size">压缩后图片的最大大小</param>
  235. /// <param name="sfsc">是否是第一次调用</param>
  236. /// <returns></returns>
  237. public static bool CompressImage(Bitmap _bitmap, string dFile, int flag = 90, int size = 300)
  238. {
  239. ////如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
  240. //FileInfo firstFileInfo = new FileInfo(sFile);
  241. //if (sfsc == true && firstFileInfo.Length < size * 1024)
  242. //{
  243. // firstFileInfo.CopyTo(dFile);
  244. // return true;
  245. //}
  246. //Image iSource = Image.FromFile(sFile);
  247. Image iSource = _bitmap;
  248. ImageFormat tFormat = iSource.RawFormat;
  249. int dHeight = iSource.Height / 2;
  250. int dWidth = iSource.Width / 2;
  251. int sW, sH;
  252. //按比例缩放
  253. System.Drawing.Size tem_size = new System.Drawing.Size(iSource.Width, iSource.Height);
  254. if (tem_size.Width > dHeight || tem_size.Width > dWidth)
  255. {
  256. if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
  257. {
  258. sW = dWidth;
  259. sH = (dWidth * tem_size.Height) / tem_size.Width;
  260. }
  261. else
  262. {
  263. sH = dHeight;
  264. sW = (tem_size.Width * dHeight) / tem_size.Height;
  265. }
  266. }
  267. else
  268. {
  269. sW = tem_size.Width;
  270. sH = tem_size.Height;
  271. }
  272. Bitmap ob = new Bitmap(dWidth, dHeight);
  273. Graphics g = Graphics.FromImage(ob);
  274. g.Clear(System.Drawing.Color.WhiteSmoke);
  275. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  276. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  277. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  278. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  279. g.Dispose();
  280. //以下代码为保存图片时,设置压缩质量
  281. EncoderParameters ep = new EncoderParameters();
  282. long[] qy = new long[1];
  283. qy[0] = flag;//设置压缩的比例1-100
  284. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  285. ep.Param[0] = eParam;
  286. try
  287. {
  288. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  289. ImageCodecInfo jpegICIinfo = null;
  290. for (int x = 0; x < arrayICI.Length; x++)
  291. {
  292. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  293. {
  294. jpegICIinfo = arrayICI[x];
  295. break;
  296. }
  297. }
  298. if (jpegICIinfo != null)
  299. {
  300. if (flag > 0)
  301. {
  302. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  303. FileInfo fi = new FileInfo(dFile);
  304. if (fi.Length > 1024 * size)
  305. {
  306. flag -= 10;
  307. CompressImage(_bitmap, dFile, flag, size);
  308. }
  309. }
  310. //ob.Save(dFile, jpegICIinfo, ep);
  311. //FileInfo fi = new FileInfo(dFile);
  312. //bool IsAgain = false;
  313. //if (fi.Length > 1024 * size)
  314. //{
  315. // fi.CopyTo(dFile + fi.Length);
  316. // fi.Delete();
  317. // Bitmap newbitmap = ReadImageFile(dFile + fi.Length);
  318. // CompressImage(newbitmap, dFile, flag, size);
  319. // FileToolsCommon.DeleteFile(dFile + fi.Length);
  320. //}
  321. }
  322. else
  323. {
  324. ob.Save(dFile, tFormat);
  325. }
  326. return true;
  327. }
  328. catch
  329. {
  330. return false;
  331. }
  332. finally
  333. {
  334. iSource.Dispose();
  335. ob.Dispose();
  336. }
  337. }
  338. #endregion 图片压缩
  339. #region 截屏指定UI控件
  340. /// <summary>
  341. /// 保存图片
  342. /// </summary>
  343. /// <param name="ui">需要截图的UI控件</param>
  344. /// <param name="filePathName">图片保存地址 命名 1.png</param>
  345. /// <param name="width">保存宽</param>
  346. /// <param name="height">保存高</param>
  347. public static void SaveUIToImage(FrameworkElement ui, string filePathName, int width, int height)
  348. {
  349. try
  350. {
  351. System.IO.FileStream fs = new System.IO.FileStream(filePathName, System.IO.FileMode.Create);
  352. RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
  353. PixelFormats.Pbgra32);
  354. bmp.Render(ui);
  355. BitmapEncoder encoder = new PngBitmapEncoder();
  356. encoder.Frames.Add(BitmapFrame.Create(bmp));
  357. encoder.Save(fs);
  358. fs.Close();
  359. }
  360. catch (Exception ex)
  361. {
  362. Console.WriteLine(ex.Message);
  363. }
  364. }
  365. #endregion
  366. }
  367. }