【问题标题】:Save non-transparent image from a PictureBox with transparent images使用透明图像保存来自 PictureBox 的非透明图像
【发布时间】:2012-03-08 00:27:22
【问题描述】:

我有一个 PictureBox,里面有很多透明的 png 被绘制到...

现在我想将这个 PictureBox 的内容保存到一个文件中,但没有透明度。

我该怎么做?

我已经尝试像这样从图像中删除透明度,但是没有用,保存后我仍然得到透明图像。

...

removeTransparency(pictureBox.Image).Save(saveFileDialog.FileName);

private Bitmap removeTransparency(Image transparentImage)
{
    Bitmap src = new Bitmap(transparentImage);
    Bitmap newImage = new Bitmap(src.Size.Width, src.Size.Height);
    Graphics g = Graphics.FromImage(newImage);
    g.DrawRectangle(new Pen(new SolidBrush(Color.White)), 0, 0, newImage.Width, newImage.Height);
    g.DrawImage(src, 0, 0);

    return newImage;
}

【问题讨论】:

    标签: c# transparency


    【解决方案1】:

    您可以循环遍历所有像素(请不要使用 GetPixel/SetPixel)来更改颜色,或者您可以创建另一个相同大小的位图,从图像创建图形上下文,使用您喜欢的背景颜色清除图像,然后在上面绘制图像(因此透明像素将被背景颜色替换)。

    示例

    你做过这样的事吗?

    public static Bitmap Repaint(Bitmap source, Color backgroundColor)
    {
     Bitmap result = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);
     using (Graphics g = Graphics.FromImage(result))
     {
      g.Clear(backgroundColor);
      g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height));
     }
    
     return result;
    }
    

    【讨论】:

    • 是的,这就是我试图在我的代码中做的,但我仍然得到相同的透明图像,不知道为什么......
    • 哦,我刚才看到了你的代码 :) 你用的是 DrawRectangle() 而不是 FillRectangle()!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2014-10-05
    相关资源
    最近更新 更多