C#压缩图片1

时间:2022-01-13 05:47:16

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace CompressedImage
{
class Program
{
static void Main(string[] args)
{
//String path = @"D:\web\web\carlife_api\UserPortrait";
String path = @"D:\备份\UserPortrait";
string[] dirs = Directory.GetDirectories(path);
List<string> Image = new List<string>();
string[] file = Directory.GetFiles(path);
for (int i = 0; i < file.Count(); i++)
{
Image.Add(file[i]);
}
for (int i = 0; i < dirs.Count(); i++)
{
string[] files = Directory.GetFiles(dirs[i]);
for (int j = 0; j < files.Count(); j++)
{
Image.Add(files[j]);
}
}
foreach (string item in Image)
{
ImageBitmap(item);
Console.Write(item);
}
}
private static void ImageBitmap(string Url)
{
try
{
System.Drawing.Image b = new System.Drawing.Bitmap(Url);
Bitmap bt = new Bitmap(b);//从指定的现有图像并使用指定的大小初始化 Bitmap 类的新实例。

if (bt.Width != 200 || bt.Height != 200)
{
bt.SetResolution(200, 200);
var bit1 = new Bitmap(bt, 200, 200);
b.Dispose();
bt.Dispose();
System.Drawing.Image newImg = bit1;

EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 90; //压缩比例,决定图片大小的重要因素。
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
bt.Dispose();//用完要释放
newImg.Save(Url, GetCodecInfo("image/jpeg"), encoderParams);//保存
newImg.Dispose();//用完要释放
Console.WriteLine(" 修改成功");
}
else
{
b.Dispose();
bt.Dispose();
Console.WriteLine(" 没有修改");
}

}
catch
{
}
}
/**/
/// <summary>
/// 保存JPG时用
/// </summary>
/// <param name="mimeType"></param>
/// <returns>得到指定mimeType的ImageCodecInfo</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}
}
}