How to implement compressing images to a fixed size in C#?

You can use the System.Drawing namespace in C# to compress images. Here is a simple example code demonstrating how to compress an image to a specified size:

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);
    }
}

In the provided example code, the CompressImage method takes the source image path, output path, and target width and height as parameters. The algorithm will calculate the appropriate image size for the target width and height, and compress the source image to save it in JPEG format at that size. You can adjust the compression quality and output format as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *