压缩图片

 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         }

 

posted @ 2015-10-14 15:42  Lyghost  阅读(256)  评论(0编辑  收藏  举报