views:

534

answers:

3

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

+6  A: 

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.

santosc
Hi Santosc, thank you very much. I have spent a whole night on this. Would provide an example how to set this up?
Daoming Yang
Can you show the code you use to save the file back out to a jpeg?
santosc
Here's an article that shows how to programmatically set the JPEG compression level: http://msdn.microsoft.com/en-us/library/bb882583.aspx
David
A: 

you probably already had jpeg with quality 75 or 85, but save it as 100 (no compression)

fazo
I did something like this, but it still the same. g.InterpolationMode = InterpolationMode.Low; g.SmoothingMode = SmoothingMode.HighSpeed; g.CompositingQuality = CompositingQuality.HighSpeed;
Daoming Yang
+4  A: 

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.

mykhal