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.
3 Answers
from PIL import Image
image = Image.new('RGB', (n, m))
-
4Thanks, and then I should save it with
image.save("image.png", "PNG")
– AmirCommented 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
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.
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")
PIL
from the tags