55

I would like to combine 4 PNG images to one PNG file. I know who to combine them with Image.paste method, but I couldn't create an save output file! Actually, I want to have a n*m empty PNG file, and use to combine my images. I need to specify the file size, if not I couldn't use paste method.

Amir
  • 1,087
  • 1
  • 9
  • 26

3 Answers3

77
from PIL import Image
image = Image.new('RGB', (n, m))
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
73

You can use the method PIL.Image.new() to create the image. But the default color is in black. To make a totally white-background empty image, you can initialize it with the code:

from PIL import Image
img = Image.new("RGB", (800, 1280), (255, 255, 255))
img.save("image.png", "PNG")

It creates an image with the size 800x1280 with white background.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
ccy
  • 1,735
  • 16
  • 19
2

Which part are you confused by? You can create new images just by doing Image.new, as shown in the docs. Anyway, here's some code I wrote a long time ago to combine multiple images into one in PIL. It puts them all in a single row but you get the idea.

max_width = max(image.size[0] for image in images)
max_height = max(image.size[1] for image in images)

image_sheet = Image.new("RGBA", (max_width * len(images), max_height))

for (i, image) in enumerate(images):
    image_sheet.paste(image, (
        max_width * i + (max_width - image.size[0]) / 2,
        max_height * 0 + (max_height - image.size[1]) / 2
    ))

image_sheet.save("whatever.png")
Antimony
  • 37,781
  • 10
  • 100
  • 107