This article is a mirror article of machine translation, please click here to jump to the original article.

View: 21852|Reply: 1

[Source] C# image compression algorithm

[Copy link]
Posted on 11/23/2015 7:31:40 PM | | |
  1. /// <summary>
  2.     /// 壓縮圖片 /// </summary>
  3.     /// <param name="fileStream">圖片流</param>
  4.     /// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param>
  5.     /// <returns></returns>
  6.     private byte[] CompressionImage(Stream fileStream, long quality) {
  7.         using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream)) {
  8.             using (Bitmap bitmap = new Bitmap(img)) {
  9.                 ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
  10.                 System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
  11.                 EncoderParameters myEncoderParameters = new EncoderParameters(1);
  12.                 EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
  13.                 myEncoderParameters.Param[0] = myEncoderParameter;
  14.                 using (MemoryStream ms = new MemoryStream()) {
  15.                     bitmap.Save(ms, CodecInfo, myEncoderParameters);
  16.                     myEncoderParameters.Dispose();
  17.                     myEncoderParameter.Dispose();
  18.                     return ms.ToArray();
  19.                 }
  20.             }
  21.         }
  22.     }
  23. 調用:CompressionImage(stream,0L)//最低質量 1M jpg圖大概能壓成180k左右
Copy code






Previous:Unsupported pixel format of the source or template image
Next:Byte[], Image, Bitmap
 Landlord| Posted on 11/24/2015 11:10:10 AM |
  1. private static ImageCodecInfo GetEncoder(ImageFormat format)
  2.         {
  3.             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
  4.             foreach (ImageCodecInfo codec in codecs)
  5.             {
  6.                 if (codec.FormatID == format.Guid)
  7.                 { return codec; }
  8.             } return null;
  9.         }
Copy code


Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com