How to save an 8-bit grayscale JPEG image?


M

moss

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?
 
Ad

Advertisements

P

Peter Duniho

moss said:
[...]
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top