我有一个 PictureBox,上面绘制了来自文件的图像,一个叠加在另一个之上(就像 photoshop 分层概念,如果您熟悉的话)。作为 PNG 并具有不透明度索引,这些图像是图像合成的完美候选者。但我不知道如何做到这一点并保存到文件中。
在下面的代码示例中,我将两个 PNG 图像加载到位图对象中,并将它们绘制在 PictureBox 上。
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Rectangle DesRec = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
Bitmap bmp;
Rectangle SrcRec;
bmp = (Bitmap)Image.FromFile(Application.StartupPath + "\\Res\\base.png");
SrcRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, DesRec, SrcRec, GraphicsUnit.Pixel);
bmp = (Bitmap)Image.FromFile(Application.StartupPath + "\\Res\\layer1.png");
SrcRec = new Rectangle(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, DesRec, SrcRec, GraphicsUnit.Pixel);
}
如何将合成保存到一个文件,最好是另一个 PNG 文件?
请您参考如下方法:
我会开始绘制到内存中的中间位图,然后保存(如果确实需要,最终会在您的图片框中绘制)。像这样:
var bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (var graphics = Graphics.FromImage(bmp))
{
// ...
graphics.DrawImage(...);
// ...
}
bmp.Save("c:\\test.png", ImageFormat.Png);
