GDI+ Bug: Anti-Aliasing White On Transparency

落爺英雄遲暮 提交于 2019-12-08 18:49:29

I had the same problem when I generated PNGs from SVGs in Mono (Mac OS X), but for some reason not on Windows.

To fix this i copied the nearest rgb values from the figure to the antialias-pixels, but keept the antialias-alpha value.

The code is based on the example from: https://msdn.microsoft.com/en-us/library/ms229672(v=vs.90).aspx

Code to run as last step before the save method:

var pxf = PixelFormat.Format32bppArgb;
var rect = new Rectangle(0, 0, image.Width, image.Height);
BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, pxf);

IntPtr ptr = bmpData.Scan0;

int numBytes = image.Width * image.Height * 4;
byte[] rgbValues = new byte[numBytes];
Marshal.Copy(ptr, rgbValues, 0, numBytes);

for (int argb = 0; argb < rgbValues.Length; argb += 4) {
    var a = rgbValues [argb + 3]; //A
    if(a > 0x00 && a < 0xFF) { //Antialiasing:
        //Scan for neares solid with 0 transparency:
        for (int i = 0; i < 3; i++) { //3 pixels scan seems to be enough

            var right = argb + i * 4;
            var left = argb - i * 4;
            var up = argb - i * image.Width * 4;
            var down = argb + i * image.Width * 4;

            if (right < rgbValues.Length && rgbValues [right + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [right + 2]; //R
                rgbValues [argb+1] = rgbValues [right + 1]; //G
                rgbValues [argb] = rgbValues [right];       //B
                break;
            } else if (left > 0 && rgbValues [left + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [left + 2];
                rgbValues [argb+1] = rgbValues [left + 1];
                rgbValues [argb] = rgbValues [left];
                break;
            } else if (up > 0 && rgbValues [up + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [up + 2];
                rgbValues [argb+1] = rgbValues [up + 1];
                rgbValues [argb] = rgbValues [up];
                break;
            } else if (down < rgbValues.Length && rgbValues [down + 3] == 0xFF) {
                rgbValues [argb+2] = rgbValues [down + 2];
                rgbValues [argb+1] = rgbValues [down + 1];
                rgbValues [argb] = rgbValues [down];
                break;
            }
        }
        //rgbValues [argb+3] = a; //Keep old alpha.
    }
}

Marshal.Copy(rgbValues, 0, ptr, numBytes);

image.UnlockBits(bmpData);

`

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!