使用c# . net从多个图像合成
本文关键字:图像 net 使用 | 更新日期: 2023-09-27 18:04:47
我有一个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);
谢谢你们。我决定按照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
)保存不透明度指数完整。