Can't set palette in bitmap

我只是一个虾纸丫 提交于 2019-11-29 03:02:21

This had me confused too. It seems bitmap.Palette returns a clone of the bitmap's palette. Once you've modified your copy, you need to reset the bitmap's pallete by using bitmap.Palette = palette, e.g.

ColorPalette palette = bitmap.Palette;
Color entries = palette.Entries;
....
entries[i] = new Color(...);
....
bitmap.Palette = palette; // The crucial statement

See http://www.charlespetzold.com/pwcs/PaletteChange.html

According to Microsoft Reference Source, Palette property of Image class in .net, internally uses GDI+ Flat APIs for handling palettes. GdipGetImagePalette used for initializing ColorPalette object in get method and GdipSetImagePalette used for writing ColorPalette object data back to device is set method.

Each time in your for loop the line bmp.Palette.Entries.SetValue(b, i); forces the Image to call GdipGetImagePalette and data of bmp.Palette reinitialized and therefore you can see no change has been made to bmp.Palette after the loop.

To solve this problem you must do the following:

  1. Assign new alias to bmp.Palette by assigning it to a variable,
  2. Modify it by new alias (this prevents reloading),
  3. And put it back to the bmp.Palette.

Code:

var newAliasForPalette = bmp.Palette; // Palette loaded from graphic device
for (int i = 0; i < 256; i++)
{
    newAliasForPalette.Entries[i] = myColor[i];
}
bmp.Palette = newAliasForPalette; // Palette data wrote back to the graphic device

In my opinion, replacement of definition of Palette as a property with GetPalette() and SetPalette() methods by Microsoft, will be a great help in avoiding confusion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!