I'm trying to manipulate an indexed image. In order to use the Graphics class, I first convert the image to a Bitmap. After the manipulation, I want to save the image back as an Indexed image. To do this I'm creating a blank Bitmap and using Graphics.DrawImage() to 'populate'. My problem is that the resulting image is blank.

Image plainImage = Image.FromFile(imageFile);
Image img = new Bitmap(plainImage);
//img = ResizeMaintainAspect(img, brdEnt.Width, brdEnt.Height, Color.Black);
Image image = new Bitmap(img.Width, img.Height, plainImage.PixelFormat);
image.Palette = plainImage.Palette;
Graphics g = Graphics.FromImage(img);
g.DrawImage(image, img.Width, img.Height);

(I commented out the manipulation routine to ensure that nothing I was doing there was causing the problem)

What am I doing wrong?!

Many thanks

Recommended Answers

All 5 Replies

You are drawing image with a Graphics object. OK.
And image is created in lines 4. OK.
In line 5 you copy the Colorpalette used in plainImage, you are not copying the "picture", hence you won't see nothing.

Thanks for the response, Danny

Perhaps I'm misunderstanding what Graphics.FromImage() does. I thought it set the context for the graphics object (including the 'picture' itself), and the subsequent DrawImage() call writes that context to the supplied 'canvas' (the empty image variable).

Is this not correct?


As far as I know that is correct. The image variable is "empty".

Woah. Ok, so this turned out to be way more complicated than I thought it would be.

Firstly, my understanding of the way FromImage() and DrawImage() works was wrong: Graphics.FromImage() sets up the 'canvas' to draw on, and DrawImage() draws a supplied image to that canvas, whereas I thought it was the other way around.

This then means that since I want the output image to be an indexed one, and the GDI+ Graphics class does not support this directly, I can't use it.

This article on CodeProject put me on the right path: In order to convert and save an indexed image from a non-indexed one, one must manually copy the image data from the src to the destination, as well as set the correct color index from the source palette. If that sounds a little vague, it's because I still need to fully understand this process.

Good news is that things are working as they should, and my manipulated image sizes are similar to the original (which was my actual goal)

Glad you learned something, I did too!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.