保存 PNG 时未保存颜色通道



我正在尝试制作一个应用程序,该应用程序从 PNG 中提取颜色并将它们放入查找纹理中,然后保存原始 PNG 的副本,该副本使用颜色通道来存储 LUT 的位置。这适用于 1D LUT,但不会为 2D LUT 保存额外的通道。

图像输出后,我将其加载到 Photoshop 中以检查通道,红色通道保存正确,但绿色通道不正确。

哪个通道似乎并不重要,出于某种原因,它不会为foundRow保存除 0 之外的任何内容,即使在调试器中单步执行时,我可以验证此特定图像的foundRow至少上升到 3。

private static bool ProcessImage(string filePath, string newPath, Color[,] colors, ref int colorsColumnIndex, ref int colorsRowIndex)
{
Console.WriteLine($"Processing file: {filePath}");
var bmp = new Bitmap(filePath);
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
var pixel = bmp.GetPixel(x, y);
var lutPixel = Color.FromArgb(pixel.R, pixel.G, pixel.B);
int foundColumn;
int foundRow;
GetColorIndexes(colors, lutPixel, out foundColumn, out foundRow);
if (foundColumn < 0 || foundRow < 0)
{
foundColumn = colorsColumnIndex;
foundRow = colorsRowIndex;
colors[foundColumn, foundRow] = lutPixel;
colorsColumnIndex++;
if (colorsColumnIndex >= 256)
{
colorsColumnIndex = 0;
colorsRowIndex++;
}
}
if (colorsColumnIndex >= 256 || colorsRowIndex >= 256)
{
Console.WriteLine($"ERROR: More than {256 * 256} colors found!");
return false;
}
//if (foundRow != 0)
//Console.Write($"Setting pixel at {x}, {y} to R: {foundColumn}, G: {foundRow}");
var newPixel = Color.FromArgb(255, foundColumn, foundRow, 0);
bmp.SetPixel(x, y, newPixel);
}
}
bmp.Save(newPath, ImageFormat.Png);
bmp.Dispose();
Console.WriteLine($"Saved {newPath}");
return true;
}

在这些行中:

var newPixel = Color.FromArgb(255, foundColumn, foundRow, 0);
bmp.SetPixel(x, y, newPixel);

如果newPixel是 ARGB(255, 1, 1, 0(,则由于某种原因,实际保存的文件结果为 ARGB(255, 1, 0, 0(

发现问题!事实证明,我最初发布的代码确实可以正常工作,但我不小心将黑色保存到了 LUT 的某些我不应该拥有的部分。如果有人感兴趣,修复程序位于此处的第 62 行。

最新更新