How to optimize an image for web?

Asked

Viewed 2,592 times

6

On my website someone uploads an image (e.g., 800x600). I would like to save this image in a folder but reducing the disk size as much as possible without losing much quality.

How can I do that?

  • 1

    You can use a compression library like LZMA (7zip) to compress the image, so you can store it taking up little disk space and maintain quality. Or they’re saved in a database?

  • 1

    If they are in PNG/JPG format, then they should already be very compact (applying another compression algorithm over the top shouldn’t make much difference). One option is to open the image and remove small differences between pixels, causing very close colors to match. This will make PNG compression much more efficient.

2 answers

14


What image formats?

One simple way to compress images is to use the namespace classes System Drawing.:

public static void ComprimirImagem(Image imagem, long qualidade, string filepath)
{
    var param = new EncoderParameters(1);
    param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualidade);
    var codec = ObterCodec(imagem.RawFormat);
    imagem.Save(filepath, codec, param);
}

private static ImageCodecInfo ObterCodec(ImageFormat formato)
{
    var codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == formato.Guid);
    if (codec == null) throw new NotSupportedException();
    return codec;
}

Adapted from here.

Theoretically the code would work with any image format that the system had codec, but according to my tests only with images in JPEG format there was compression (the others kept the same size regardless of the quality passed).

I did some tests with this image (265.94 KB), the results were:

  • Quality 80L: 54.3 KB (image)
  • Quality 60L: 40.6 KB (image)
  • Quality 40L: 33.5 KB (image)
  • Quality 20L: 25.4 KB (image)

P.S.: The images of the posted links do not represent exactly the quality I obtained in my tests, because the Mgur has also made its own optimization; it is just to get a sense of the quality loss.


Other references

1

The example of Talles, correct, the conversion to the other models is enough to pass as the code below.

var codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.