如何在 Python 中创建一个空的 n*m PNG 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12760389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create an empty n*m PNG file in Python?
提问by Amir
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 pastemethod.
我想将 4 张 PNG 图像合并为一个 PNG 文件。我知道谁将它们与 Image.paste 方法结合起来,但我无法创建保存输出文件!实际上,我想要一个*m 的空 PNG 文件,并用于组合我的图像。我需要指定文件大小,否则我无法使用粘贴方法。
采纳答案by John La Rooy
from PIL import Image
image = Image.new('RGB', (n, m))
回答by Antimony
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.
你对哪个部分感到困惑?您只需执行 即可创建新图像Image.new,如文档中所示。无论如何,这是我很久以前写的一些代码,用于在 PIL 中将多个图像合并为一个。它将它们全部放在一行中,但您明白了。
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")
回答by ccy
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:
您可以使用该方法PIL.Image.new()来创建图像。但是默认颜色是black。要制作全白背景的空图像,您可以使用以下代码对其进行初始化:
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.
它创建一个大小为 800x1280 的白色背景图像。

