|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Drawing; |
| 4 | +using System.Drawing.Imaging; |
| 5 | +using System.IO; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace Server.StreamLibrary |
| 11 | +{ |
| 12 | + public class JpgCompression : IDisposable |
| 13 | + { |
| 14 | + private readonly ImageCodecInfo _encoderInfo; |
| 15 | + private readonly EncoderParameters _encoderParams; |
| 16 | + |
| 17 | + public JpgCompression(long quality) |
| 18 | + { |
| 19 | + EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); |
| 20 | + this._encoderInfo = GetEncoderInfo("image/jpeg"); |
| 21 | + this._encoderParams = new EncoderParameters(2); |
| 22 | + this._encoderParams.Param[0] = parameter; |
| 23 | + this._encoderParams.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionRle); |
| 24 | + } |
| 25 | + |
| 26 | + public void Dispose() |
| 27 | + { |
| 28 | + Dispose(true); |
| 29 | + |
| 30 | + GC.SuppressFinalize(this); |
| 31 | + } |
| 32 | + |
| 33 | + protected virtual void Dispose(bool disposing) |
| 34 | + { |
| 35 | + if (disposing) |
| 36 | + { |
| 37 | + if (_encoderParams != null) |
| 38 | + { |
| 39 | + _encoderParams.Dispose(); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public byte[] Compress(Bitmap bmp) |
| 45 | + { |
| 46 | + using (MemoryStream stream = new MemoryStream()) |
| 47 | + { |
| 48 | + bmp.Save(stream, _encoderInfo, _encoderParams); |
| 49 | + return stream.ToArray(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public void Compress(Bitmap bmp, ref Stream targetStream) |
| 54 | + { |
| 55 | + bmp.Save(targetStream, _encoderInfo, _encoderParams); |
| 56 | + } |
| 57 | + |
| 58 | + private ImageCodecInfo GetEncoderInfo(string mimeType) |
| 59 | + { |
| 60 | + ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders(); |
| 61 | + int num2 = imageEncoders.Length - 1; |
| 62 | + for (int i = 0; i <= num2; i++) |
| 63 | + { |
| 64 | + if (imageEncoders[i].MimeType == mimeType) |
| 65 | + { |
| 66 | + return imageEncoders[i]; |
| 67 | + } |
| 68 | + } |
| 69 | + return null; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments