c#圖片壓縮到固定大小怎么實(shí)現(xiàn)

c#
小億
238
2024-03-07 13:38:28

你可以使用C#中的System.Drawing命名空間來實(shí)現(xiàn)圖片的壓縮。下面是一個(gè)簡(jiǎn)單的示例代碼,演示如何將圖片壓縮到指定的大?。?/p>

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方法接受源圖片的路徑、輸出路徑以及目標(biāo)寬度和高度作為參數(shù)。算法會(huì)計(jì)算出適合目標(biāo)寬度和高度的圖片尺寸,并將源圖片按照這個(gè)尺寸進(jìn)行壓縮保存為JPEG格式。您可以根據(jù)需要調(diào)整壓縮質(zhì)量和輸出格式。

0