How to optimize an image for web?

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

How can I do this?

Author: BrunoLM, 2013-12-15

2 answers

What image formats?

A simple way to compress images is to use the System namespace classes.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 got in my tests, since imgur did also its own optimization; it's just to have a notion of loss of quality.


Other references

 14
Author: talles, 2013-12-15 18:44:49

The example of talles, is correct, the conversion to the other models just in the formed pass as the code below.

var codec = ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);
 1
Author: Ueslei Fernando, 2017-08-08 14:03:20