Problem with PNG images in C #

Work in Visual Studio 2008. I am trying to draw a PNG image and save this 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 a solution does not make mistakes. When I try to run it, I get the following:

Unable to create graphic from image with indexed pixel format.

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

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

So, if I cannot use the Graphics class, what am I using?

EDIT2: after reading this , I'm sure I'm sure it is better to use JPG files when working with GDI +, no?

EDIT3: my service statements:

 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; 
+7
c # image png graphics
source share
2 answers

Without the best PNG library that supports indexed PNGs, you're out of luck trying to draw to this image, because obviously the GDI + graphic does not support indexed images.

If you do not need to use indexed PNGs, you can capture this error and convert your input to regular RGB PNGs using a third-party utility.

edit:

I found this link http://fci-h.blogspot.com/2008/02/c-indexed-pixel-problem.html , which gives a method of drawing on your image, however this will not affect the original, just a copy that you can save () if you need.

If the link goes down:

 Bitmap bm = (Bitmap) System.Drawing.Image.FromFile("Fci-h.jpg",true); Bitmap tmp=new Bitmap (bm.Width ,bm.Height ); Graphics grPhoto = Graphics.FromImage(tmp); grPhoto.DrawImage(bm, new Rectangle(0, 0, tmp.Width , tmp.Height ), 0, 0, tmp.Width , tmp.Height , GraphicsUnit.Pixel); 
+9
source share

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

 Image img = Image.FromFile("file.png"); img = new Bitmap(img); newGraphics = Graphics.FromImage(img); 
+12
source share

All Articles