壓縮圖片

 1 /// <summary>
 2         /// 壓縮圖片
 3         /// </summary>
 4         /// <param name="fileByte">圖片字節數組</param>
 5         /// <param name="quality">壓縮質量0-100之間,數值越大質量越高</param>
 6         /// <returns></returns>
 7         public static byte[] CompressionImage(byte[] fileByte, long quality)
 8         {
 9             using (MemoryStream fileStream = new MemoryStream(fileByte))
10             {
11                 using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
12                 {
13                     using (Bitmap bitmap = new Bitmap(img))
14                     {
15                         ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
16                         System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
17                         EncoderParameters myEncoderParameters = new EncoderParameters(1);
18                         EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
19                         myEncoderParameters.Param[0] = myEncoderParameter;
20                         using (MemoryStream ms = new MemoryStream())
21                         {
22                             bitmap.Save(ms, CodecInfo, myEncoderParameters);
23                             myEncoderParameters.Dispose();
24                             myEncoderParameter.Dispose();
25                             return ms.ToArray();
26                         }
27                     }
28                 }
29             }
30         }
31         /// <summary>
32         /// 獲取指定圖片編碼信息
33         /// </summary>
34         /// <param name="format"></param>
35         /// <returns></returns>
36         private static ImageCodecInfo GetEncoder(ImageFormat format)
37         {
38             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
39             foreach (ImageCodecInfo codec in codecs)
40             {
41                 if (codec.FormatID == format.Guid)
42                 {
43                     return codec;
44                 }
45             }
46             return null;
47         }
相關文章
相關標籤/搜索