Convert 8 bit grayscale image to 8 bit grayscale jpg in .Net 2.0

We have a system that provides images in 8-bit grayscale or tiff or jpg formats. However, the component that we have to process the images expects the image to be in 8-bit jpg format.

When I use .Net to save tiff images as jpg, it casts it in 24 bit image.

Is there a hopefully simple and quick way to convert 8-bit grayscale images to an equivalent jpg?

+3


source to share


2 answers


I tried to just conclude that I'm sorry: the .Net library. The bitmap class does NOT store JPEG as 8bpp even when explicitly specified and the data is in grayscale.

(note: although it is indicated in some places, the JPEG format supports 8bpp).

In Convert Image to Grayscale, you can find the snipet code to convert to grayscale any image.

Using this code, I was able to save an 8bpp grayscale image instance with a ".jpeg" extension, but by specifying ImageFormat.Gif ... which cheat ...

My results show that the solution is a completely different approach.

The FreeImage library offers powerful APIs, including the function you need to solve your problem.



The home page is at http://freeimage.sourceforge.net/faq.html

But I was unable to compile it on Win2008 + VS 2010 machine.

You have to work hard to make it work in a modern environment.

Some hints on how to do this are at http://www.sambeauvois.be/blog/2010/05/freeimage-and-x64-projects-yes-you-can/

Good luck!

+1


source


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

      

...



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

return bmp;
}

      

0


source







All Articles