使用C#项目写一个图片压缩
时间: 2024-11-25 10:31:27 浏览: 45
在C#中,我们可以使用System.Drawing命名空间下的Image类以及其派生类,如Bitmap,来进行图片的压缩操作。以下是一个简单的示例,展示如何使用Lanczos算法减小图片尺寸并保存为新的文件,同时保持相对较好的图像质量:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
public void CompressImage(string inputFilePath, string outputFilePath)
{
// 加载原始图片
Bitmap originalImage = new Bitmap(inputFilePath);
// 创建一个新的Bitmap对象,用于存储压缩后的图片
Bitmap compressedImage = new Bitmap(originalImage.Width / 2, originalImage.Height / 2);
using (Graphics graphics = Graphics.FromImage(compressedImage))
{
// 设置高质量压缩模式
graphics.CompressionQuality = CompressionQuality.High;
// 绘制缩小的图像
graphics.DrawImage(originalImage, 0, 0, compressedImage.Width, compressedImage.Height,
0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, ColorMatrix.Empty);
}
// 保存压缩后的图片
compressedImage.Save(outputFilePath, ImageFormat.Jpeg); // 或者其他格式如.Png, .Bmp等
// 关闭资源
originalImage.Dispose();
compressedImage.Dispose();
}
```
在这个例子中,我们首先创建了一个与原图大小的一半的新图片,然后通过Graphics对象将原图缩放到新图片上。最后,我们将压缩后的图片保存到指定路径。
阅读全文
相关推荐


















