使用C# Graphics类复制图片时边框白色像素伪影的解决方法
解决C# Graphics复制透明PNG后的伪影问题
问题核心在于Bitmap像素格式不匹配和透明通道合成逻辑错误,通过调整代码可以彻底解决伪影问题,具体方案如下:
关键修改点
- 保留原图片的像素格式
默认创建Bitmap时可能会丢失原图片的Alpha通道细节,需直接复用源图的像素格式:
var output = new Bitmap(source.Width, source.Height, source.PixelFormat);
- 强制保留Alpha通道的颜色矩阵
通过ColorMatrix确保ImageAttributes不修改透明通道的信息,避免默认的颜色校正破坏边缘的半透明像素:
var colorMatrix = new ColorMatrix(new float[][] { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); ia.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
- 优化Graphics的绘制参数
移除对图片无效的文本渲染设置,调整合成模式和插值逻辑,避免引入额外模糊:
g.CompositingMode = CompositingMode.SourceOver; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.SmoothingMode = SmoothingMode.None; // 像素级复制无需抗锯齿,避免边缘伪影
- 明确指定PNG格式保存
避免系统自动转换格式导致的通道丢失:
output.Save(outFile, ImageFormat.Png);
完整修改后的代码
using System.Drawing; using System.Drawing.Imaging; private void Copy(string inFile, string outFile) { using var source = Image.FromFile(inFile); // 保留原图片像素格式 var output = new Bitmap(source.Width, source.Height, source.PixelFormat); using var ia = new ImageAttributes(); // 设置颜色矩阵保留Alpha通道 var colorMatrix = new ColorMatrix(new float[][] { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); ia.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); using var g = Graphics.FromImage(output); // 优化Graphics参数 g.CompositingMode = CompositingMode.SourceOver; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.SmoothingMode = SmoothingMode.None; g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, ia); // 明确指定PNG格式保存 output.Save(outFile, ImageFormat.Png); }
额外说明
- 你之前尝试的
TextRenderingHint、SmoothingMode.AntiAlias等参数对像素图复制无效,甚至会引入边缘模糊伪影,因此需要移除。 - 导入Unity后,建议检查TextureImporter设置:勾选Alpha Is Transparency,Filter Mode根据需求选择
Point(像素风格)或Bilinear,进一步减少伪影。
内容的提问来源于stack exchange,提问作者sinedsem
相关产品推荐
相关产品推荐

