用C# 写一个图片按比例压缩的算法
时间: 2024-01-03 08:05:33 浏览: 39
以下是一个简单的图片按比例压缩的算法示例,基于C#语言实现:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
public static Image CompressImage(Image image, int maxWidth, int maxHeight)
{
int width = image.Width;
int height = image.Height;
if (width <= maxWidth && height <= maxHeight)
{
return image;
}
int newWidth, newHeight;
if (width * maxHeight > height * maxWidth)
{
newWidth = maxWidth;
newHeight = height * maxWidth / width;
}
else
{
newHeight = maxHeight;
newWidth = width * maxHeight / height;
}
var destRect = new Rectangle(0, 0, newWidth, newHeight);
var destImage = new Bitmap(newWidth, newHeight);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, width, height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
```
使用方法:
```csharp
Image originalImage = Image.FromFile("original.jpg");
Image compressedImage = CompressImage(originalImage, 800, 600);
compressedImage.Save("compressed.jpg", ImageFormat.Jpeg);
```
其中,`CompressImage`方法接收三个参数:原始图片、目标宽度和目标高度。如果原始图片的宽度和高度都小于等于目标宽度和目标高度,则直接返回原始图片。否则,根据原始图片的宽高比例,计算出新的宽度和高度,然后使用`Graphics`对象将原始图片缩放到目标大小,并返回缩放后的新图片。最后,将新图片保存在磁盘上。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)