Click here to Skip to main content
15,919,774 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I need a sample code which sets the palette for an image?

Thanks in advance
Posted

1 solution

Assuming you already have a 8-bits per pixel bitmap (a bitmap created with PixelFormat.Format8bppIndexed):
C#
// the colors array must contain 256 colors
void ChangePalette(Bitmap image, Color[] colors)
{
     ColorPalette palette = image.Palette;
     for (int i = 0; i < 256; i++)
          palette.Entries[i] = colors[i];
     image.Palette = palette;
}


------------------------------------------

how can i change my bitmap image to PixelFormat.Format8bppIndexed?

Just create a new Bitmap:
C#
Bitmap image = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

To fill this bitmap:
C#
//lock the bitmap so we can edit its pixels
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
BitmapData bmpData = image.LockBits(rect, ImageLockMode.WriteOnly, image.PixelFormat);
//allocate memory for the pixels
byte[] values = new byte[bmpData.Stride * bmpData.Height];
//fill the pixels
for (int y = 0; y < bmpData.Height; y++)
    for (int x = 0; x < bmpData.Width; x++)
        values[y * bmpData.Stride + x] = 0;
//copy the new pixels into the bitmap
System.Runtime.InteropServices.Marshal.Copy(values, 0, bmpData.Scan0, values.Length);
//unlock the bitmap
image.UnlockBits(bmpData);
 
Share this answer
 
v2
Comments
yeshgowda 29-Jul-11 5:52am    
Bitmap image has PixelFormat.Format24bppRgb,how can i change my bitmap image to PixelFormat.Format8bppIndexed?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900