C# Make one picture using various pictures
-
06-09-2019 - |
Question
Imagine that I have a matrix of 2x2 or 3x3 pictures and I want to make one big picture using these 4 or 9 pictures. I want to show this picture on a pictureBox.
I'm developing a Windows Mobile App.
How can I do this?
Edit: Moved comments to question for clarification..
Normally you asing an image to a pictureBox like this pictureBox.image = myImage
. I want to build myImage using 4 images. Imagine that I have a image and cut it out in four squared pieces. I want to use these 4 images to re-assamble the original one.
Thank you!
Solution
Something like this:
Bitmap bitmap = new Bitmap(totalWidthOfAllImages, totalHeightOfAllImages);
using(Graphics g = Graphics.FromBitmap(bitmap))
{
foreach(Bitmap b in myBitmaps)
g.DrawImage(/* do positioning stuff based on image position */)
}
pictureBox1.Image = bitmap;
OTHER TIPS
Either place 4 och 9 PictureBoxes next to each other or use a Panel instead of a PictureBox and draw all images in the Panles Paint event using Graphics.DrawImage.
This should work, but is untested:
private Image BuildBitmap(Image[,] parts) {
// assumes all images are of equal size, assumes arrays are 0-based
int xCount = parts.GetUpperBound(0) + 1;
int yCount = parts.GetUpperBound(0) + 1;
if (xCount <= 0 || yCount <= 0)
return null; // no images to join
int width = parts[0,0].Width;
int height = parts[0,0].Height;
Bitmap newPicture = new Bitmap(width * xCount, height * yCount);
using (Graphics g = Graphics.FromImage(newPicture)) {
for (int x = 0; x < xCount; x++)
for (int y = 0; y < yCount; y++)
g.DrawImage(parts[x, y], x * width, y & height);
}
return newPicture;
}