Reputation: 188
I'm trying to find a way to merge two Bitmaps together in a Paint event. My code looks like this:
private void GraphicsForm_Paint(object sender, PaintEventArgs e)
{
try
{
Bitmap1 = new Bitmap(1366, 768);
Bitmap2 = new Bitmap(1366, 768);
OutputBitmap = ...//and this is where I've stuck :(
}
catch
{
}
}
The problem is more problematic, because the Graphics object which draws onto Bitmap2 is in an other class. I also want Bitmap2 to be drawn behind Bitmap1 on the OutputBitmap.
Can anyone give me a good advice how to merge these two Bitmaps (behind eachother, but) onto one output bitmap?
Thanks :)
Upvotes: 1
Views: 13572
Reputation: 1164
public static Bitmap Combine(params Bitmap[] sources)
{
List<int> imageHeights = new List<int>();
List<int> imageWidths = new List<int>();
foreach (Bitmap img in sources)
{
imageHeights.Add(img.Height);
imageWidths.Add(img.Width);
}
Bitmap result = new Bitmap(imageWidths.Max(), imageHeights.Max());
using (Graphics g = Graphics.FromImage(result))
{
foreach (Bitmap img in sources)
g.DrawImage(img, Point.Empty);
}
return result;
}
Enjoy...
Upvotes: 0
Reputation: 81675
Assuming your bitmaps have transparent areas, try creating one bitmap and draw the other two bitmaps into it in the order you want:
private Bitmap MergedBitmaps(Bitmap bmp1, Bitmap bmp2) {
Bitmap result = new Bitmap(Math.Max(bmp1.Width, bmp2.Width),
Math.Max(bmp1.Height, bmp2.Height));
using (Graphics g = Graphics.FromImage(result)) {
g.DrawImage(bmp2, Point.Empty);
g.DrawImage(bmp1, Point.Empty);
}
return result;
}
Upvotes: 3