【问题标题】:How to make a System.Drawing.Image semitransparent?如何使 System.Drawing.Image 半透明?
【发布时间】:2011-01-13 03:33:09
【问题描述】:

System.Drawing.Graphics.DrawImage 将一张图片粘贴到另一张图片上。但我找不到透明度选项。

我已经在图像中绘制了我想要的所有东西,我只想让它半透明(alpha-transparency)

【问题讨论】:

  • @Mitch Wheat - 这个问题是针对 GIF 的
  • GIF 不具备半透明性。我在这里谈论的是 PNG
  • 发布您正在使用的代码,并向我们提供有关您希望合并的图像的一些详细信息,我们可能会提供帮助。

标签: .net image graphics transparency alpha


【解决方案1】:

我从 Mitch 的链接中复制了一个我认为对我有用的答案:

public static Bitmap SetOpacity(this Bitmap bitmap, int alpha)
{
    var output = new Bitmap(bitmap.Width, bitmap.Height);
    foreach (var i in Enumerable.Range(0, output.Palette.Entries.Length))
    {
        var color = output.Palette.Entries[i];
        output.Palette.Entries[i] =
            Color.FromArgb(alpha, color.R, color.G, color.B);
    }
    BitmapData src = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadOnly,
        bitmap.PixelFormat);
    BitmapData dst = output.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.WriteOnly,
        output.PixelFormat);
    bitmap.UnlockBits(src);
    output.UnlockBits(dst);
    return output;
}

【讨论】:

    【解决方案2】:

    没有“透明度”选项,因为您尝试做的是称为 Alpha 混合。

    public static class BitmapExtensions
    {
        public static Image SetOpacity(this Image image, float opacity)
        {
            var colorMatrix = new ColorMatrix();
            colorMatrix.Matrix33 = opacity;
            var imageAttributes = new ImageAttributes();
            imageAttributes.SetColorMatrix(
                colorMatrix,
                ColorMatrixFlag.Default,
                ColorAdjustType.Bitmap);
            var output = new Bitmap(image.Width, image.Height);
            using (var gfx = Graphics.FromImage(output))
            {
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.DrawImage(
                    image,
                    new Rectangle(0, 0, image.Width, image.Height),
                    0,
                    0,
                    image.Width,
                    image.Height,
                    GraphicsUnit.Pixel,
                    imageAttributes);
            }
            return output;
        }
    }
    

    Alpha Blending

    【解决方案3】:
    private Image GetTransparentImage(Image image, int alpha)
    {
        Bitmap output = new Bitmap(image);
    
        for (int x = 0; x < output.Width; x++)
        {
            for (int y = 0; y < output.Height; y++)
            {
                Color color = output.GetPixel(x, y);
                output.SetPixel(x, y, Color.FromArgb(alpha, color.R, color.G, color.B));
            }
        }
    
        return output;
    }
    

    【讨论】:

    • 这不是绘制图像的好方法。逐个像素地做这对性能来说会很糟糕。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多