views:

756

answers:

2

Working in Visual Studio 2008. I'm trying to draw on a PNG image and save that image again.

I do the following:

private Image img = Image.FromFile("file.png");
private Graphics newGraphics;

And in the constructor:

newGraphics = Graphics.FromImage(img);

Building the solution gives no errors. When I try to run it, I get this:

A Graphics object cannot be created from an image that has an indexed pixel format.

I don't have much experience with using images in C#. What does this mean and how can I remedy this?

EDIT: through debugging, Visual Studio tells me that the image has a format8bppindexed Pixel Format.

So if I can't use the Graphics class, what do I use?

EDIT2: After reading this, I think it's safe to assume that I better stick to JPG files when working with GDI+, no?

EDIT3: my using-statements:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
+3  A: 

You cannot create a graphics from an indexed image format (PNG, GIF,...). You should use a Bitmap (file or convert your image to a bitmap).

Image img = Image.FromFile("file.png");
img = new Bitmap(img);
newGraphics = Graphics.FromImage(img);
Guillaume
Indeed, dead link there.
WebDevHobo
Perhaps I don't have a the needed "using" statement, but Visual Studio doesn't recognise that function.
WebDevHobo
Which function ?
Guillaume
As per the docs, this won't work with an Indexed image http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx
badbod99
badbod99 > You missed the img = new Bitmap(img);
Guillaume
You're 100% right!!! It works perfectly, tried with PNG and Indexed bitmaps.
badbod99
It's within the System.Drawing namespace. http://msdn.microsoft.com/en-us/library/system.drawing.image.fromfile.aspx
badbod99
+3  A: 

Without a better PNG library that supports indexed PNGs you're out of luck trying to draw to that image since evidently the GDI+ graphics object doesn't support indexed images.

If you don't need to use indexed PNGs you could trap that error and convert your input to regular RGB PNGs using a 3rd party utility.

edit:

I did find this link http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html that gives a method to draw on your image, however it won't affect the original, just a copy you can Save() if you require.

Ron Warholic
GDI+ doesn't support creating a graphics context from them which has the same effect for the OP. Anyways, here's a decent link for a workaround solution:http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html
Ron Warholic
That blogpost did it. Thanks.
WebDevHobo