星火微课系统客户端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ImageHelper.cs 14KB

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