【发布时间】:2020-06-23 07:27:17
【问题描述】:
我已将带有唯一调色板的索引彩色图像 (8bppI) 加载到 C# 程序中,我需要访问该图像中颜色的 索引。但是,唯一的访问函数似乎是返回颜色而不是索引的 Bitmap.GetPixel(x,y)。当相同的颜色被插入到相同格式和调色板的位图中时,颜色信息显然被误解为索引,一切都搞砸了。为了清楚起见,这是代码的简化版本:
public void CreateTerrainMap() {
visualization = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
visualizationLock = new LockBitmap(visualization);
Lock();
// "TerrainIndex.bmp" is a 256x256 indexed colour image (8bpp) with a unique palette.
// Debugging confirms that this image loads with its palette and format intact
Bitmap terrainColours = new Bitmap("Resources\\TerrainIndex.bmp");
visualization.Palette = terrainColours.Palette;
Color c;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (Terrain[x, y] < SeaLevel) {
c = Color.FromArgb(15); // Counterintuitively, this actually gives index 15 (represented as (0,0,0,15))
} else {
heatIndex = <some number between 0 and 255>;
rainIndex = <some number between 0 and 255>;
if (IsCoastal(x, y)) {
c = Color.FromArgb(35); // Counterintuitively, this actually gives index 35 (represented as (0,0,0,35))
} else {
// This returns an argb colour rather than an index...
c = terrainColours.GetPixel(rainIndex, heatIndex);
}
}
// ...and this seemingly decides that the blue value is actually an index and sets the wrong colour entirely
visualizationLock.SetPixel(x, y, c);
}
}
}
TerrainIndex 如下所示: TerrainIndex.bmp
调色板如下所示:Palette
输出应如下所示:Good
但它看起来像这样:Bad
请注意,海洋(索引 15)和海岸(索引 35)看起来是正确的,但其他所有内容都来自调色板的错误部分。
我找不到任何有关在 C# 中使用索引颜色位图的有用信息。我真的希望有人可以向我解释我可能做错了什么,或者指出我正确的方向。
【问题讨论】:
-
this library 有帮助吗?它有一个
GetColorIndex方法,可用于任何索引位图,但也支持索引像素格式的Get/SetColor。另请参阅示例here。 -
位图bmp文件是一个字节数组。结构见 Wiki:en.wikipedia.org/wiki/BMP_file_format
标签: c# bitmap color-palette