仅CPU实现ARGB位图合成异常问题排查
ARGB位图合成异常排查求助
我在合成多张ARGB位图时得到异常结果,预期为手动实现的效果,当前合成结果不符合预期。
以下是我编写的C#代码片段:
public static void Composite(this byte[] input, byte[] layer, int x, int y, int width, int height) { int w = width; if (w > RewBatch.width) { w = RewBatch.width; } Parallel.For(0, height, j => { for (int i = 0; i < w; i += 4) { int whoAmI = (y + j) * w + (x + i); if (whoAmI < 0 || whoAmI > input.Length) { continue; } Pixel _one = Pixel.Extract32bit(input, whoAmI); Pixel _two = Pixel.Extract32bit(layer, j * width + i); if (_two.A < 255) { Color blend = _two.color.Blend(_one.color, 0.15d); input[whoAmI] = blend.B; input[whoAmI + 1] = blend.G; input[whoAmI + 2] = blend.R; input[whoAmI + 3] = blend.A; } else { input[whoAmI] = 255; input[whoAmI + 1] = _two.color.R; input[whoAmI + 2] = _two.color.G; input[whoAmI + 3] = _two.color.B; } } }); }
问题排查与修正建议
索引计算错误:
whoAmI的计算逻辑错误,input数组的行偏移应该用原始位图宽度×4(每个像素占4字节),而非裁剪后的w。正确索引计算应为:int rowStride = RewBatch.width * 4; int whoAmI = (y + j) * rowStride + (x * 4) + i;原代码用
w计算行偏移会导致像素位置错位,这是结果异常的核心原因。颜色通道赋值颠倒:else分支中ARGB字节顺序完全错误,.NET中32位ARGB位图的字节存储顺序为B、G、R、A,修正后:
input[whoAmI] = _two.color.B; input[whoAmI + 1] = _two.color.G; input[whoAmI + 2] = _two.color.R; input[whoAmI + 3] = 255; // _two.A为255,直接赋值边界判断不严谨:原判断
whoAmI > input.Length未考虑每个像素占4字节,应改为:if (whoAmI < 0 || whoAmI + 3 >= input.Length)避免数组越界访问。
混合逻辑不符合预期:当前混合使用固定系数0.15,若预期是根据图层的Alpha值进行混合,应替换为
_two.A / 255.0作为混合参数,而非固定值。线程安全确认:确保
RewBatch.width是只读的共享变量,避免Parallel.For执行过程中被修改导致异常。
内容的提问来源于stack exchange,提问作者DaFuze
相关产品推荐
相关产品推荐

