你可以使用C#中的System.Drawing命名空間來實現圖片的壓縮。下面是一個簡單的示例代碼,演示如何將圖片壓縮到指定的大小:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public class ImageCompressor
{
public void CompressImage(string sourcePath, string outputPath, int maxWidth, int maxHeight)
{
using (Image sourceImage = Image.FromFile(sourcePath))
{
double aspectRatio = (double)sourceImage.Width / sourceImage.Height;
int newWidth = maxWidth;
int newHeight = (int)(maxWidth / aspectRatio);
if (newHeight > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)(maxHeight * aspectRatio);
}
using (Bitmap compressedImage = new Bitmap(newWidth, newHeight))
{
using (Graphics graphics = Graphics.FromImage(compressedImage))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(sourceImage, 0, 0, newWidth, newHeight);
}
compressedImage.Save(outputPath, ImageFormat.Jpeg);
}
}
}
}
class Program
{
static void Main()
{
ImageCompressor compressor = new ImageCompressor();
compressor.CompressImage("source.jpg", "compressed.jpg", 800, 600);
}
}
在上面的示例代碼中,CompressImage
方法接受源圖片的路徑、輸出路徑以及目標寬度和高度作為參數。算法會計算出適合目標寬度和高度的圖片尺寸,并將源圖片按照這個尺寸進行壓縮保存為JPEG格式。您可以根據需要調整壓縮質量和輸出格式。