I am getting error:
"A Graphics object cannot be created from an image that has an indexed pixel format."
in function:
public static void AdjustImage(ImageAttributes imageAttributes, Image image)
{
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
Graphics g = Graphics.FromImage(image);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);
g.Dispose();
}
I would like to ask you, how can I fix it?
The simplest way is to create a new image like this:
It creates a new image exactly like the original was with all its contents.
Overall, if you want to work with indexed images and actually preserve their colour depth and palette, this will always mean writing explicit checks and special code for them.
Graphics
simply can't work with them, because it manipulates colours, and the actual pixels of indexed images contain no colours, just indices.For anyone still seeing this all these years later... the valid way to paint an image onto an existing (8-bit) indexed image is this:
It's not an easy task, but it's certainly possible. If the pasted image is also indexed, and contains more than 256 pixels, you can speed up the process by doing the colour matching on the palette instead of on the actual image data, then getting the backing bytes from the other indexed image, and remapping them using the created mapping.
Note that all of this only applies to eight bit. If your image is four-bit or one-bit, the simplest way to handle it is to convert it to 8-bit first so you can handle it as one byte per pixel, and convert it back afterwards.
For more information on that, see How can I work with 1-bit and 4-bit images?
Refering to this, it can be solved by creating a blank bitmap with the same dimensions and the correct PixelFormat and the draw on that bitmap.