What are the methods for compressing images in C#?

In C#, you can use the Bitmap class from the System.Drawing namespace to compress images. Here is a simple example code demonstrating how to compress an image using the Bitmap class.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public static void CompressImage(string sourceImagePath, string outputImagePath, long quality)
{
    using (Bitmap sourceImage = new Bitmap(sourceImagePath))
    {
        ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);

        sourceImage.Save(outputImagePath, jpgEncoder, encoderParameters);
    }
}

private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

    foreach (var codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }

    return null;
}

In the example above, the CompressImage method takes three parameters: the sourceImagePath for the original image, the outputImagePath for the compressed image, and the quality of the compression. Within the method, the original image is first loaded using the Bitmap class, then the compression encoder and parameters are set, and finally the compressed image is saved to the specified path.

It is important to note that the range of values for the quality parameter is usually between 0 and 100, where a higher value indicates better image quality. The value of quality can be adjusted based on individual needs to achieve the appropriate compression effect.

广告
Closing in 10 seconds
bannerAds