Home > OS >  How to merge 4 images both vertically and horizontally
How to merge 4 images both vertically and horizontally

Time:12-07

I have an array called imgarr which consists of 4 images in bytes. The image sizes are same but unknown. How can I merge it into the following format?

 ---- ---- 
|img0|img1|
 ---- ---- 
|img2|img3|
 ---- ---- 

The output resolution should be 4 times the size of one imgarr image and no borders are needed.

EDIT: my code now:

from PIL import Image
import io

#convert bytes to image
for i in imgarr:
    stream = io.BytesIO(rimg)
    image = Image.open(stream).convert("RGBA").save("tempimg\\temp{}.png".format(i))
    stream.close()

img0 = Image.open("tempimg\\temp0.png")
img1 = Image.open("tempimg\\temp1.png")
img2 = Image.open("tempimg\\temp2.png")
img3 = Image.open("tempimg\\temp3.png")
image1_size = img0.size
new_image = Image.new('RGB',(2*image1_size[0], 2*image1_size[1]), (250,250,250))
new_image.paste(img0,(0,0))
new_image.paste(img1,(image1_size[0],0))
new_image.paste(img2,(0,image1_size[1]))
new_image.paste(img3, (image1_size[0],image1_size[1]))

new_image.save("tempimg\\temp.png")

but the output image is very weird.

CodePudding user response:

Here's a simple 2x2 collage from the same photo.

from PIL import Image, ImageDraw

collage = Image.new("RGB", (1000,1000), color=(255,255,255))
photo = Image.open("23988930.jpg")
photo = photo.resize((500,500))
# paste images in 2x2 collage
collage.paste(photo, (0,0))
collage.paste(photo, (0,500))
collage.paste(photo, (500,0))
collage.paste(photo, (500,500))

collage.show()

In your case, all you need is to do is specify the starting point (top-left-corner) for each image in collage.

from PIL import Image, ImageDraw

photo = Image.open("23988930.jpg")
width, height = photo.size

collage = Image.new("RGB", (2*width,2*height), color=(255,255,255))
# paste images in 2x2 collage
collage.paste(photo, (0,0))
collage.paste(photo, (0,height))
collage.paste(photo, (width,0))
collage.paste(photo, (width,height))

collage.show()
  • Related