C#需要设计一段图片批量压缩并批量保存的代码
时间: 2023-06-19 08:08:48 浏览: 53
以下是使用 C# 编写的批量压缩图片并批量保存的代码:
``` csharp
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ImageCompression
{
class Program
{
static void Main(string[] args)
{
// 设置要压缩的图片路径
string imagePath = @"C:\Images\";
// 获取指定路径下的所有图片文件
string[] imageFiles = Directory.GetFiles(imagePath, "*.jpg");
// 设置压缩后的图片保存路径
string savePath = @"C:\CompressedImages\";
// 设置压缩质量,0-100,数值越小压缩越严重
int quality = 50;
foreach (string imageFile in imageFiles)
{
// 加载图片
using (Image image = Image.FromFile(imageFile))
{
// 设置压缩格式
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1];
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
// 设置压缩后的文件名
string saveFile = savePath + Path.GetFileNameWithoutExtension(imageFile) + "_compressed.jpg";
// 保存压缩后的图片
image.Save(saveFile, codec, parameters);
}
}
// 压缩完成
System.Console.WriteLine("Compression completed.");
System.Console.ReadLine();
}
}
}
```
注意事项:
1. 代码中使用的是 JPG 格式的图片,如果需要处理其他格式的图片,可以修改代码中的后缀名。
2. 压缩质量越小,图片文件越小,但是图片的清晰度也会下降,可以根据自己的需求调整。
3. 保存压缩后的图片时,需要指定保存的文件名,可以根据自己的需求修改保存路径和文件名。