首页 > 解决方案 > 保存PNG时未保存颜色通道

问题描述

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

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

哪个通道似乎无关紧要,由于某种原因,它不会为 0 保存任何内容foundRow,即使在调试器中单步执行时,我可以验证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)

标签: c#.net-coresystem.drawing

解决方案


发现问题!原来我最初发布的代码确实可以正常工作,但我不小心将黑色保存到我不应该拥有的 LUT 的某些部分中。如果有人感兴趣修复在第 62 行。


推荐阅读