简体   繁体   English

从PictureBox保存具有透明图像的非透明图像

[英]Save non-transparent image from a PictureBox with transparent images

I have a PictureBox with lots of transparent png's drawn into... 我有一个PictureBox,其中有很多透明png绘制到...

Now I'd like to save the content of this PictureBox to a file, but without the transparency. 现在,我想将此PictureBox的内容保存到一个文件中,但是没有透明度。

How can I do this? 我怎样才能做到这一点?

I have already tried to remove transparency from the Image like this, but it didn't work, I still got a transparent image after the save. 我已经尝试过像这样从图像中删除透明图像,但是它没有用,保存后我仍然得到透明图像。

...

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;
}

You may cycle through all pixel (please not using GetPixel/SetPixel) to change the color or you may create another bitmap with the same size, create a graphics context from the image, clear the image with your favorite background color and then draw your image on it (so transparent pixels simply will be replaced by the background color). 您可以循环显示所有像素(请不要使用GetPixel / SetPixel)以更改颜色,也可以创建具有相同大小的另一个位图,从图像中创建图形上下文,用您喜欢的背景色清除图像,然后绘制图像在其上(因此透明像素将简单地替换为背景色)。

Example

Did you do something like this? 你做了这样的事吗?

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM