views:

31

answers:

1

Hello,

I need to convert 24- and 32-bits jpeg and png-files to a lower bit depth (16). I found some code to do this, but the resulting images keep the bit depth of the original file although there file size is lower.

Image img = Image.FromFile(filePathOriginal);
Bitmap bmp = ConvertTo16bpp(img);
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 16);
bmp.Save(filePathNew, jpgCodec, parameters);
bmp.Dispose();
img.Dispose();

...

private static Bitmap ConvertTo16bpp(Image img) {
    var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
    using (var gr = Graphics.FromImage(bmp))
    {
         gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
    }

    return bmp;
}

Any ideas what's going wrong?

Thanks, Frank

+2  A: 

JPEG is a three-color format. It usually has 8 bits per color, but can have 12 or 16. 24=3x8 bits of color is therefore reasonable, but 16 or 32 is simply impossible. It just doesn't divide by three. 3x16=48 would be possible, but that's a higher color depth. JPEG is designed for photo's, and it doesn't make sense to support lower bit depths than 3x8. There's no benefit in that.

Now, what is the 16 bit image in your code? It's an imprecise in-memory approximation of the original, using only 65535 colors. When you save that back, you get a 24 bits JPEG. Apparently your JPEG encoder doesn't know how to create an 48 bits JPEG. Even if it did, it would be a waste of bits since the in-memory image only has 65536 colors anyway.

To summarize: what is going wrong is the task. There's no such thing as a 65536 color JPEG.

MSalters
thanks msalters. I can follow the logic of your answer. If I compare the original and converted image, they have both 24 bit depth, but the filesize is reduced with a test image from 2218 kb to 959 kb. When I compare the image quality, there is not much difference, only the converted one is a little bit darker.
Frank
other difference: with png, the transparancy is lost
Frank