1 C#图片无损压缩
2
3 //引用命名空间
4 using System.Drawing.Imaging;
5 using System.Drawing;
6 using System.Drawing.Drawing2D;
7
8 #region GetPicThumbnail
9 /// <summary>
10 /// 无损压缩图片
11 /// </summary>
12 /// <param name="sFile">原图片</param>
13 /// <param name="dFile">压缩后保存位置</param>
14 /// <param name="dHeight">高度</param>
15 /// <param name="dWidth"></param>
16 /// <param name="flag">压缩质量 1-100</param>
17 /// <returns></returns>
18
19 public bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
20 {
21 System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
22
23 ImageFormat tFormat = iSource.RawFormat;
24
25 int sW = 0, sH = 0;
26
27 //按比例缩放
28
29 Size tem_size = new Size(iSource.Width, iSource.Height);
30
31
32
33 if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
34 {
35
36 if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
37 {
38
39 sW = dWidth;
40
41 sH = (dWidth * tem_size.Height) / tem_size.Width;
42
43 }
44
45 else
46 {
47
48 sH = dHeight;
49
50 sW = (tem_size.Width * dHeight) / tem_size.Height;
51
52 }
53
54 }
55
56 else
57 {
58
59 sW = tem_size.Width;
60
61 sH = tem_size.Height;
62
63 }
64
65 Bitmap ob = new Bitmap(dWidth, dHeight);
66
67 Graphics g = Graphics.FromImage(ob);
68
69 g.Clear(Color.WhiteSmoke);
70
71 g.CompositingQuality = CompositingQuality.HighQuality;
72
73 g.SmoothingMode = SmoothingMode.HighQuality;
74
75 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
76
77 g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
78
79 g.Dispose();
80
81 //以下代码为保存图片时,设置压缩质量
82
83 EncoderParameters ep = new EncoderParameters();
84
85 long[] qy = new long[1];
86
87 qy[0] = flag;//设置压缩的比例1-100
88
89 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
90
91 ep.Param[0] = eParam;
92
93 try
94 {
95
96 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
97
98 ImageCodecInfo jpegICIinfo = null;
99
100 for (int x = 0; x < arrayICI.Length; x++)
101 {
102
103 if (arrayICI[x].FormatDescription.Equals("JPEG"))
104 {
105
106 jpegICIinfo = arrayICI[x];
107
108 break;
109
110 }
111
112 }
113
114 if (jpegICIinfo != null)
115 {
116
117 ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
118
119 }
120
121 else
122 {
123
124 ob.Save(dFile, tFormat);
125
126 }
127
128 return true;
129
130 }
131
132 catch
133 {
134
135 return false;
136
137 }
138
139 finally
140 {
141
142 iSource.Dispose();
143
144 ob.Dispose();
145
146 }
147
148
149
150 }
151 #endregion