How to optimize an image for web?

5

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

How can I do this?

    
asked by anonymous 15.12.2013 / 18:01

2 answers

13

What image formats?

A 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 JPEG images there was compression (the others remained the same size regardless of the quality passed).

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

PS: The images of the posted links do not represent exactly the quality I got in my tests, since the imgur also made its own optimization; it's just to get a sense of quality loss.

Other references

15.12.2013 / 19:44
1

The example of talles, okay, 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);
    
08.08.2017 / 16:03