【问题标题】:Create image with transparent background using GDI+?使用 GDI+ 创建具有透明背景的图像?
【发布时间】:2010-10-17 01:39:54
【问题描述】:

我正在尝试创建具有透明背景的图像以显示在网页上。
我尝试了几种技术,但背景总是黑色。
如何创建透明图像,然后在其上绘制一些线条?

【问题讨论】:

    标签: c# asp.net gdi+


    【解决方案1】:

    这可能会有所帮助(我将 Windows 窗体的背景设置为透明图像的东西放在一起:

    private void TestBackGround()
        {
            // Create a red and black bitmap to demonstrate transparency.            
            Bitmap tempBMP = new Bitmap(this.Width, this.Height);
            Graphics g = Graphics.FromImage(tempBMP);
            g.FillEllipse(new SolidBrush(Color.Red), 0, 0, tempBMP.Width, tempBMP.Width);
            g.DrawLine(new Pen(Color.Black), 0, 0, tempBMP.Width, tempBMP.Width);
            g.DrawLine(new Pen(Color.Black), tempBMP.Width, 0, 0, tempBMP.Width);
            g.Dispose();
    
    
            // Set the transparancy key attributes,at current it is set to the 
            // color of the pixel in top left corner(0,0)
            ImageAttributes attr = new ImageAttributes();
            attr.SetColorKey(tempBMP.GetPixel(0, 0), tempBMP.GetPixel(0, 0));
    
            // Draw the image to your output using the transparancy key attributes
            Bitmap outputImage = new Bitmap(this.Width,this.Height);
            g = Graphics.FromImage(outputImage);
            Rectangle destRect = new Rectangle(0, 0, tempBMP.Width, tempBMP.Height);
            g.DrawImage(tempBMP, destRect, 0, 0, tempBMP.Width, tempBMP.Height,GraphicsUnit.Pixel, attr);
    
    
            g.Dispose();
            tempBMP.Dispose();
            this.BackgroundImage = outputImage;
    
        }
    

    【讨论】:

    • 太复杂了,没必要这样做:)
    【解决方案2】:

    致电Graphics.Clear(Color.Transparent) 以清除图像。不要忘记使用具有 Alpha 通道的像素格式创建它,例如PixelFormat.Format32bppArgb。像这样:

    var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb);
    using (var g = Graphics.FromImage(image)) {
        g.Clear(Color.Transparent);
        g.DrawLine(Pens.Red, 0, 0, 135, 135);
    }
    

    假设您是 using System.DrawingSystem.Drawing.Imaging

    编辑:似乎您实际上并不需要Clear()。只需使用 Alpha 通道创建图像就会创建一个空白(完全透明)图像。

    【讨论】:

    • 我想我错过了位图构造函数的重载。不幸的是,我现在没有可用的代码,我今晚试试……
    • 比你说的有点多,但我做了一些研究并让它发挥作用。谢谢。
    • 真的还有更多吗?我完全按照您在我的代码示例中看到的做了,并且使用 alpha 通道渲染得很好。
    • more 与 gdi 无关。事实上,我正在使用它来将图像呈现到 ASP.Net 页面。问题是我将图像(以 png 格式)直接保存到响应流中,但这不适用于 png,我必须先将其保存到内存流中。
    • 就我而言,我还需要做image.MakeTransparent();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2012-05-26
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多