How to load Transparent PNG to Bitmap and ignore alpha channel

前端 未结 1 524
渐次进展
渐次进展 2021-01-25 07:47

I see many questions about how to load a PNG with an alpha channel and display it, but none about how to load a PNG that has an alpha channel but ignore the alpha channel, revea

相关标签:
1条回答
  • 2021-01-25 08:31

    Try this extension method:

        public static void SetAlpha(this Bitmap bmp, byte alpha)
        {
            if(bmp == null) throw new ArgumentNullException("bmp");
    
            var data = bmp.LockBits(
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                System.Drawing.Imaging.ImageLockMode.ReadWrite,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    
            var line = data.Scan0;
            var eof = line + data.Height * data.Stride;
            while(line != eof)
            {
                var pixelAlpha = line + 3;
                var eol = pixelAlpha + data.Width * 4;
                while(pixelAlpha != eol)
                {
                    System.Runtime.InteropServices.Marshal.WriteByte(
                        pixelAlpha, alpha);
                    pixelAlpha += 4;
                }
                line += data.Stride;
            }
            bmp.UnlockBits(data);
        }
    

    Usage:

    var pngImage = new Bitmap("filename.png");
    pngImage.SetAlpha(255);
    
    0 讨论(0)
提交回复
热议问题