0%

c#压缩图片

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
 using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Image_Compression
{
public class Image_Compression
{

 

static void Main(string[] args)
{
//原图片路径
string OldImgPath = @"C:\Users\98468\Desktop\tu\";
//保存压缩后图片路径
string NewImgPath = @"C:\Users\98468\Desktop\su\";
//压缩质量(数字越小压缩率越高)1-100
int ImgQuality = 90;
//压缩图片最大大小
int ImgSize = 200;
//最大分辨率高 默认是0
int resolution_Max_H = 1024;
//最大分辨率宽 默认是0
int resolution_Max_W = 1024;
//调用压缩图片方法
Image_Compression_Main(OldImgPath, NewImgPath, ImgSize, ImgQuality, resolution_Max_H, resolution_Max_W);
}
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="OldImgPath">原图片路径</param>
/// <param name="NewImgPath">保存压缩后图片路径</param>
/// <param name="ImgSize">压缩图片最大大小</param>
/// <param name="ImgQuality">压缩质量(数字越小压缩率越高)1-100</param>
/// <param name="resolution_Max_H">最大分辨率高 默认是0</param>
/// <param name="resolution_Max_W">最大分辨率宽 默认是0</param>
public static void Image_Compression_Main(string OldImgPath, string NewImgPath, int ImgSize, int ImgQuality = 90, int resolution_Max_H = 0, int resolution_Max_W = 0)
{
//获取图片文件路径
DirectoryInfo path = new DirectoryInfo(OldImgPath);
//遍历指定路径目录下文件
foreach (FileInfo File in path.GetFiles())
{
//规定输入文件格式
if (File.Extension == ".Png" || File.Extension == ".png" || File.Extension == ".Jpg" || File.Extension == ".jpg" || File.Extension == ".JPEG" || File.Extension == ".jpeg")
{
//分辨率处理
int resolution_Min_Multiple = 2;
//拼接具体的文件路径
string FilePath = OldImgPath + File.Name;
//文件大小
double FileSize = GetFileSize(FilePath);
Console.WriteLine(FileSize);
if (1 - FileSize < 0)
{
if ((1 - (FileSize / 100))-1 < -10)//1000MB之外
{
Console.WriteLine($@"图片:'{FilePath}'太大了!");
}
else if ((1 - (FileSize / 100)) <= 0 && (1 - (FileSize / 100))-1 > -10)//1000MB之内
{
resolution_Min_Multiple = 16;
}
else if ((1 - (FileSize / 10)) <= 0 && (1 - (FileSize / 10))-1 > -10)//100以内
{
resolution_Min_Multiple = 8;
}
else if ((1 - FileSize) <= 0 && (1 - FileSize)-1 < -1)//10以内
{
resolution_Min_Multiple = 4;
}
}
else if (FileSize < ImgSize /1024)//如果太小则不压缩直接传递
{
File.CopyTo(NewImgPath+Path.GetFileNameWithoutExtension(File.Name)+".jpg",true);
Console.WriteLine($@"图片:'{File.Name}'压缩完成!");
continue;
}
//判断文件大小,确定是否压缩,如果大小满足则直接保存到新路径,如果不满足则进行压缩操作
if (CompressImage(FilePath, NewImgPath + Path.GetFileNameWithoutExtension(File.Name) + ".jpg", resolution_Max_H, resolution_Max_W, resolution_Min_Multiple, ImgQuality, ImgSize))//压缩成功
{

Console.WriteLine($@"图片:'{File.Name}'压缩完成!");
}
else //压缩失败
{
Console.WriteLine($@"图片:'{File.Name}'压缩失败!");
}
}
}
}
/// <summary>
/// 获取图片文件大小
/// </summary>
/// <param name="path">图片路径</param>
/// <returns></returns>
private static double GetFileSize(string path)
{
System.IO.FileInfo fileInfo = null;
try
{
fileInfo = new System.IO.FileInfo(path);
}
catch (Exception e)
{
Console.WriteLine($@"获取图片{path}大小失败 Getcatch");
Console.WriteLine(e);
return 0;
}
if (fileInfo != null && fileInfo.Exists)
{
//所得文件MB大小
double Length = (System.Math.Floor(fileInfo.Length / 1024.0 / 1024.0) + System.Math.Floor(fileInfo.Length / 1024.0 % 1024.0 / 10) / 100);
if (Length > 1000)
{
return 0;
}
return Length;
}
else
{
Console.WriteLine($@"获取图片{path}大小失败 Getelse");
return 0;
}
}
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片地址</param>
/// <param name="dFile">保存压缩后图片路径</param>
/// <param name="resolution_Max_H">最大分辨率高</param>
/// <param name="resolution_Max_W">最大分辨率宽</param>
/// <param name="resolution_Min_Multiple">分辨率缩小倍数</param>
/// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
/// <param name="size">压缩后图片的最大大小</param>
/// <returns></returns>
private static bool CompressImage(string sFile, string dFile, int resolution_Max_H = 0, int resolution_Max_W = 0, int resolution_Min_Multiple = 1, int flag = 90, int size = 300)
{
Image iSource = Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
#region 旧代码
//设置图片高宽
int dHeight = iSource.Height / resolution_Min_Multiple;//分辨率高度
int dWidth = iSource.Width / resolution_Min_Multiple; //分辨率宽度
//判断是否为手动设置最大分辨率高宽
//判断处理后的分辨率高度是否大于手动设置的分辨率高度,如果大于则设置为指定高度
if (resolution_Max_H != 0 && iSource.Height / resolution_Min_Multiple > resolution_Max_H)
{
//赋值为手动设置的分辨率的高
dHeight = resolution_Max_H;
}
//判断处理后的分辨率宽度是否大于手动设置的分辨率宽度,如果大于则设置为指定宽度
if (resolution_Max_W != 0 && iSource.Width / resolution_Min_Multiple > resolution_Max_W)
{
//赋值为手动设置的分辨率的宽
dWidth = resolution_Max_W;
}
if (resolution_Max_H == 0 && resolution_Max_W == 0)//如果为空则继续赋值为原处理后的分辨率高宽
{
dHeight = iSource.Height / resolution_Min_Multiple;//分辨率高度
dWidth = iSource.Width / resolution_Min_Multiple; //分辨率宽度
}
#endregion

 

Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);

g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//绘制图片
#region 旧代码
g.DrawImage(iSource, new Rectangle(0, 0, dWidth, dHeight), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
#endregion

g.Dispose();

//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;

try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
{
flag = flag - 10;
CompressImage(sFile, dFile, resolution_Max_H, resolution_Max_W, resolution_Min_Multiple, flag, size);
}
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ",堆栈:" + ex.StackTrace + "InnerException:" + ex.InnerException);
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}

 

}

 

class A
{
static void Main1(string[] args)
{
string pathPerc = @"C:\Users\98468\Desktop\su\1.jpg";
string source = @"C:\Users\98468\Desktop\tu\微信图片_20200723111503.jpg";
if (!File.Exists(pathPerc))
{
File.Create(pathPerc).Close();
}
else
{
File.Delete(pathPerc);
File.Create(pathPerc).Close();
}
getThumImage(source, 50, 2, pathPerc);
}

#region getThumImage
/**/
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="sourceFile">原始图片文件</param>
/// <param name="quality">质量压缩比</param>
/// <param name="multiple">收缩倍数</param>
/// <param name="outputFile">输出文件名</param>
/// <returns>成功返回true,失败则返回false</returns>
public static bool getThumImage(String sourceFile, long quality, int multiple, String outputFile)
{
try
{
long imageQuality = quality;
Bitmap sourceImage = new Bitmap(sourceFile);
ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
myEncoderParameters.Param[0] = myEncoderParameter;
float xWidth = sourceImage.Width;
float yWidth = sourceImage.Height;
Bitmap newImage = new Bitmap((int)(xWidth / multiple), (int)(yWidth / multiple));
Graphics g = Graphics.FromImage(newImage);

g.DrawImage(sourceImage, 0, 0, xWidth / multiple, yWidth / multiple);
g.Dispose();
newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
return true;
}
catch
{
return false;
}
}
#endregion getThumImage

/**/
/// <summary>
/// 获取图片编码信息
/// </summary>
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}


}
}