Home > database >  merge two picturebox and save
merge two picturebox and save

Time:07-19

I am developing a c# windows form application.. I want to merge two picturebox and save it to custom file location.. I used following code to do it. But it only save 2nd picturebox image. Could anybody tell me how to merge this two picturebox and save it..

        {
            // open file dialog   
            OpenFileDialog open = new OpenFileDialog();
            // image filters  
            open.Filter = "Image Files(*.jpg; *.jpeg; *.gif;*.png; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp;*.png";
            if (open.ShowDialog() == DialogResult.OK)
            {
                // display image in picture box  
                pictureBox2.Image = new Bitmap(open.FileName);
                //combine two images
                
                // image file path  
                textBox1.Text = open.FileName;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "JPG(*.JPG)|*.jpg";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                previewimg.Image.Save(dialog.FileName);
                pictureBox2.Image.Save(dialog.FileName);
            }
        }
    }

CodePudding user response:

Maybe need some adjustements (not tested) but I think it's useful:

using (var src1 = new Bitmap(@"c:\...\image1.png"))
using (var src2 = new Bitmap(@"c:\...\image2.png"))
using (var bmp = new Bitmap(src1.Width   src2.Width, src1.Height, PixelFormat.Format32bppPArgb))
using (var g = Graphics.FromImage(bmp))
{
    g.Clear(Color.Black);
    g.DrawImage(src1, new Rectangle(0, 0, src1.Width, src1.Height));
    g.DrawImage(src2, new Rectangle(src1.Width, 0, src2.Width, src2.Height));
    bmp.Save(@"c:\...\combined.png", ImageFormat.Png);
}

UPDATE

private void button2_Click(object sender, EventArgs e)
{
    SaveFileDialog dialog = new SaveFileDialog();
    dialog.Filter = "JPG(*.JPG)|*.jpg";
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        var src1 = previewimg.Image;
        var src2 = pictureBox2.Image;

        using (var bmp = new Bitmap(src1.Width   src2.Width, src1.Height, PixelFormat.Format32bppPArgb))
        using (var g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.Black);
            g.DrawImage(src1, new Rectangle(0, 0, src1.Width, src1.Height));
            g.DrawImage(src2, new Rectangle(src1.Width, 0, src2.Width, src2.Height));
            bmp.Save(@"c:\...\combined.png", ImageFormat.Png);
        }
    }
}
  • Related