我有一个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文件?
答案 0 :(得分:3)
我会开始绘制到一个中间内存位图,然后我会保存(最后在你的图片框中绘制,如果真的需要的话)。像这样:
var bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using (var graphics = Graphics.FromImage(bmp))
{
// ...
graphics.DrawImage(...);
// ...
}
bmp.Save("c:\\test.png", ImageFormat.Png);
答案 1 :(得分:1)
谢谢你们两位。我决定按照Efran Cobisi的建议去做,并改变了程序,以便它首先在内存中进行编写。然后我可以在任何地方使用它,无论我想要什么。
我反映变化的新代码如下 -
// Image objects to act as layers (which will hold the images to be composed)
Image Layer0 = new Bitmap(Application.StartupPath + "\\Res\\base.png");
Image Layer1 = new Bitmap(Application.StartupPath + "\\Res\\layer1.png");
//Creating the Canvas to draw on (I'll be saving/using this)
Image Canvas = new Bitmap(222, 225);
//Frame to define the dimentions
Rectangle Frame = new Rectangle(0, 0, 222, 225);
//To do drawing and stuffs
Graphics Artist = Graphics.FromImage(Canvas);
//Draw the layers on Canvas
Artist.DrawImage(Layer0, Frame, Frame, GraphicsUnit.Pixel);
Artist.DrawImage(Layer1, Frame, Frame, GraphicsUnit.Pixel);
//Free up resources when required
Artist.dispose();
//Show the Canvas in a PictureBox
pictureBox1.Image = Canvas;
//Save the Canvas image
Canvas.Save("MYIMG.PNG", ImageFormat.Png);
显然,图像(Canvas
)正在保存,不透明度指数保持不变。