How can I create an empty n*m PNG file in Python?

Question:

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.

Asked By: Amir

||

Answers:

from PIL import Image
image = Image.new('RGB', (n, m))
Answered By: John La Rooy

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")
Answered By: Antimony

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 800×1280 with white background.

Answered By: ccy