tags:

views:

542

answers:

2

I'm using this code to convert a jpg image into a png 8. The code works but the image looks grainy. I did an export in Photoshop as png 8 and it looks smoother and no grain.

Note: 8-bit png

Any image gurus out there that can help?

My code:

Image ImageFile = Image.FromFile(@"C:\Documents and Settings\dvela\My Documents\Downloads\pngtest\Batman01.jpg");
Rectangle NewSize = new Rectangle();
NewSize.Width = 112;
NewSize.Height = (NewSize.Width * ImageFile.Height) / ImageFile.Width;

Bitmap image = new Bitmap(NewSize.Width, NewSize.Height);

Graphics graphics = Graphics.FromImage(image);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;

graphics.DrawImage(ImageFile, NewSize);

FormatConvertedBitmap fcb = new FormatConvertedBitmap(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(image.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(NewSize.Width, NewSize.Height)), PixelFormats.Indexed8, BitmapPalettes.Halftone256Transparent, 0.5);

PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Interlace = PngInterlaceOption.Off;
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(fcb));

using (Stream fileStream = File.Open(@"C:\Documents and Settings\dvela\My Documents\Downloads\pngtest\test.png", FileMode.Create))
{
   pngBitmapEncoder.Save(fileStream);
}
+3  A: 

You are using a fixed palette with 256 colors for your converted image. Photoshop probably uses a palette that is created specially for that image and contains all of it's colors (or most of them).

You could use dithering, or somehow generate a custom palette, or both.

some more information is also here.

cube
I compared the color tables in Photoshop and your right there different. Are there any libraries out there that can create a custom palette?
Donny V.
I don't know C# at all, so i can't help you with this.
cube
+1 for pointing me in the right direction and giving me the correct verbage, so I could find my answer.
Donny V.
Now that i see the almost fleeting mention of it being 8-bit, i take a 2nd look at notice the Halftone256Transparent pallet. Better to have it some some adapative pallet, or use dithering, or both.
Ian Boyd
+1  A: 

I found this library that does Palette-based and Octree-based color Quantization. http://www.waterwijkers.nl/bip

This article has a great demo app that shows you how to use it. http://www.aspfree.com/c/a/C-Sharp/Lossless-Image-Resizing-in-C-Sharp/2/

This MSDN article explains the difference between the algorithms with code. http://msdn.microsoft.com/en-us/library/aa479306.aspx

Donny V.