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