Python PIL | Image.new() 方法
PIL 是Python Imaging Library,它为Python解释器提供了图像编辑功能。
PIL.Image.new()方法创建具有给定模式和大小的新图像。大小以(宽度,高度)元组的形式给出,以像素为单位。颜色作为单波段图像的单个值和多波段图像的元组(每个波段一个值)给出。
我们也可以使用颜色名称。如果省略颜色参数,则图像用零填充(这通常对应于黑色)。如果颜色为无,则图像未初始化。如果您要在图像中粘贴或绘制东西,这可能很有用。
Syntax:
PIL.Image.new(mode, size)
PIL.Image.new(mode, size, color)
Parameters:
mode: The mode to use for the new image. (It could be RGB, RGBA)
size: A 2-tuple containing (width, height) in pixels.
color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.
Return Value: An Image object.
代码#1:
Python3
# Imports PIL module
import PIL
# creating a image object (new image object) with
# RGB mode and size 200x200
im = PIL.Image.new(mode="RGB", size=(200, 200))
# This method will show image in any image viewer
im.show()
Python3
# imports Pil module
import PIL
# creating image object which is of specific color
im = PIL.Image.new(mode = "RGB", size = (200, 200),
color = (153, 153, 255))
# this will show image in any image viewer
im.show()
输出:
代码#2:
Python3
# imports Pil module
import PIL
# creating image object which is of specific color
im = PIL.Image.new(mode = "RGB", size = (200, 200),
color = (153, 153, 255))
# this will show image in any image viewer
im.show()
输出:
可以更改颜色元组的值以获得不同的颜色,或者我们可以简单地使用颜色名称(对于单波段图像)。