C# JPG压缩算法
时间: 2023-11-15 14:07:01 浏览: 42
C#中有多种方法可以进行JPG压缩。其中一种常用的方法是使用System.Drawing命名空间中的Image类和EncoderParameters类来实现。以下是一个示例代码,展示了如何使用这种方法来进行JPG压缩:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
public void CompressJpeg(string sourcePath, string outputPath, long quality)
{
using (Bitmap image = new Bitmap(sourcePath))
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
image.Save(outputPath, jpgEncoder, parameters);
}
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
```
这个代码片段中的CompressJpeg方法接收三个参数:源文件路径、输出文件路径和质量参数。质量参数的取值范围是0-100,其中0代表最低质量,100代表最高质量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)