Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# why resize image will increase the file size

I have image file which is 6k jpg file with width: 172px and hight: 172px.

I use the following code try to resize it to 128*128px jpg file:

public static Image ResizeImage(Image img, int width, int height)
    {
        var b = new Bitmap(width, height, PixelFormat.Format24bppRgb);

        using (Graphics g = Graphics.FromImage(b))
        {
            g.DrawImage(img, 0, 0, width, height);
        }

        return b;
    }

This code has strangely increased the file size to 50k, can any one explain why? and how to resize the image to 128*128px and keep the size about 6k.

Many thanks.

DY

like image 771
Daoming Yang Avatar asked Dec 18 '09 23:12

Daoming Yang


2 Answers

It depends on the algorithm that was used to compress the jpeg file. Certain algorithms are more lossy (lose image quality) than others but benefit from a smaller size.

What's happening is that in code, the jpeg is being expanded into a bitmap while in memory. When it went to save the 128x128 jpeg out, the code used an algorithm which does less compressing than the one used to save the original picture. This caused it to produce a larger jpeg file, even though the image size itself is smaller.

like image 61
santosc Avatar answered Sep 20 '22 00:09

santosc


In the code posted, you are not returning JPEG file, but bitmap (128x128 24bpp uncompressed bitmap has size 48kB). You have to compress it again, this tutorial might help.

like image 28
mykhal Avatar answered Sep 19 '22 00:09

mykhal