为什么我的位图图像在将32位转换为8位后有另一种颜色覆盖



我正在调整位图图像的大小,并将位图图像转换为8位(灰度)。但我有一个问题,当我将32位图像转换为8位图像时,结果有另一种颜色覆盖,而它在24位图像上工作得很好。我猜原因在alpha颜色。但我不知道问题到底出在哪里。

这是我生成8位调色板颜色的代码,并将其写在DIB之后部分:
char* palette = new char[1024];
for (int i = 0; i < 256; i++) {
palette[i * 4] = palette[i * 4 + 1] = palette[i * 4 + 2] = (char)i;
palette[i * 4 + 3] = 255;
}
fout.write(palette, 1024);
delete[] palette;

正如我所说,我的代码在24位上工作得很好。在32位中,颜色在调整大小后仍然保持不变,但当转换为8位时,它看起来像这样:期望的图像(从24位转换时)//意外的图像(当从32位转换时)

这就是我如何获得颜色并保存到srcPixel[]:

int i = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = getIndex(width, x, y);
srcPixel[index].A = srcBMP.pImageData[i];
i += alpha;
srcPixel[index].B = srcBMP.pImageData[i++];
srcPixel[index].G = srcBMP.pImageData[i++];
srcPixel[index].R = srcBMP.pImageData[i++];
}
i += padding;
}

这是我通过从srcPixel[]中得到A B G R四种颜色的平均值来转换的代码:

int i = 0;
for (int y = 0; y < dstHeight; y++) {
for (int x = 0; x < dstWidth; x++) {
int index = getIndex(dstWidth, x, y);
dstBMP.pImageData[i++] = (srcPixel[index].A + srcPixel[index].B + srcPixel[index].G + srcPixel[index].R) / 4;
}
i += dstPadding;
}

如果我在我的代码中删除并跳过所有alpha字节,当转换我的图像时仍然是这样的,我将有另一个问题是当调整大小时,我的图像将有另一个颜色覆盖,就像转换到8位时的问题:没有alpha通道调整大小。

如果我跳过alpha通道,而获得平均(改变为dstBMP.pImageData[i++] = (srcPixel[index].B + srcPixel[index].G + srcPixel[index].R) / 3),有几乎没有什么不同,覆盖仍然存在。

如果我删除palette[i * 4 + 3] = 255;或对它做任何事情,结果仍然不受影响。

非常感谢。

你添加alpha通道的颜色,这就是为什么它变得更亮。从这里我发现不透明是255,透明是0 -因此你添加另一个通道,设置为"白色"到你的结果。

从你的方程中删除alpha通道,看看我是否正确。

最新更新