61

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.

1
  • 1
    @Antimony, I guess PIL from the tags Commented Oct 6, 2012 at 13:58

3 Answers 3

84
from PIL import Image
image = Image.new('RGB', (n, m))
2
  • 4
    Thanks, and then I should save it with image.save("image.png", "PNG")
    – Amir
    Commented Oct 6, 2012 at 14:06
  • It creates all black image by default. So to be more explicit about the color of the empty image one can use image = Image.new('RGB', (n, m), color='black') Commented Jan 25 at 11:06
80

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.

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.