How to save an 8-bit grayscale JPEG image?

  • Follow


Hi,
I have a problem with saving JPEG images in 8-bit indexed pixel
format. When I save a bitmap in any other format (gif, tiff, png, bmp)
everything works ok, but for some reason it doesn't work on JPEGs...
This is the code I use for saving bitmaps:

MemoryStream mss = new MemoryStream();
FileStream fs = new FileStream(filepath, FileMode.Create,
FileAccess.ReadWrite);

            if (format == ImageFormat.Jpeg)
            {

                ImageCodecInfo[] codecs =
ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                        ici = codec;
                }

                EncoderParameters ep = new EncoderParameters(2);
                ep.Param[0] = new
EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)85);
                if(MyBitmap.PixelFormat ==
PixelFormat.Format8bppIndexed)
                {
                    ep.Param[1] = new
EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L);
                }
                else
                    ep.Param[1] = new
EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L);
                MyBitmap.Save(mss, ici, ep);
            }
            else
                MyBitmap.Save(mss, format);

            byte[] array = mss.ToArray();
            fs.Write(array, 0, array.Length);

            mss.Close();
            fs.Close();
            mss.Dispose();
            fs.Dispose();

In the debugger I can see that the in-memory bitmap is in
Format8bppIndexed, so the line that executes is this one:

ep.Param[1] = new
EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L);

But this has no effect on the output JPEG file. Any ideas why?
0
Reply moss 12/14/2009 7:59:02 PM

moss wrote:
> [...]
> In the debugger I can see that the in-memory bitmap is in
> Format8bppIndexed, so the line that executes is this one:
> 
> ep.Param[1] = new
> EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L);
> 
> But this has no effect on the output JPEG file. Any ideas why?

AFAIK, JPEG doesn't support indexed image formats.  The image is 
probably getting converted back to an RGB format as part of the save.

You can Google for documentation on the JPEG format to confirm.

Pete
0
Reply Peter 12/14/2009 8:27:59 PM


1 Replies
3136 Views

(page loaded in 0.055 seconds)


Reply: