Why does SolidBrush result in a pattern?
I am trying to dynamically generate a gif image of a given size and color in a HttpHandler. For some reason, the image is being generated with a modified color pattern and not the solid color that I was expecting SolidBrush to create . The following code is the simplest I can find, which exposes the problem.
private void GenerateSquareImage(String filename, String color, Int32 width)
{
Bitmap img = new Bitmap(width, width);
Graphics g = Graphics.FromImage(img);
SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml("#" + color));
g.FillRectangle(brush, 0, 0, width, width);
img.Save(filename, System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
brush.Dispose();
g.Dispose();
}
Here is an example of the results I get when passing "415976" as a color parameter:
imageshack http://img148.imageshack.us/img148/8936/colorcb5.png
(On the left is the HTML SPAN block with the background color set to # 415976. The block on the right is my graphic where you can see the colored colors.)
The result is the same if I use this code:
g.Clear(ColorTranslator.FromHtml("#" + color));
instead of calling g.FillRectangle in the above method.
UPDATE: By default, GDI + saves GIFs with a Web Safe Palette if any programmatic changes are made to Bitmap. This is what made me ignore the unsafe palette color. I was able to change the code given in Marco's post below ( http://msdn.microsoft.com/en-us/library/aa479306.aspx ) to change the palette on my newly created image so that my color is respected.
source to share
Or you can look here for a solution using a complex quantizer to create a custom palette (I don't take responsibility for the code in the link, never tried it myself).
This other link from Microsoft has a detailed analysis of the issue.
Hope it helps.
source to share