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?
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?
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:
80L
: 54.3 KB (image)60L
: 40.6 KB (image)40L
: 33.5 KB (image)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 c# image-compression
You are not signed in. Login or sign up in order to post.
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?
– Zignd
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.
– Guilherme Bernal