Problem with PNG images in C#

前端 未结 2 1589
醉梦人生
醉梦人生 2021-02-14 16:34

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(\"fil         


        
相关标签:
2条回答
  • 2021-02-14 17:18

    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.

    In case 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);
    
    0 讨论(0)
  • 2021-02-14 17:29

    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);
    
    0 讨论(0)
提交回复
热议问题