Python PIL | Image.frombuffer() 方法
PIL 是Python Imaging Library,它为Python解释器提供了图像编辑功能。 Image
模块提供了一个同名的类,用于表示 PIL 图像。该模块还提供了许多工厂函数,包括从文件加载图像和创建新图像的函数。
PIL.Image.frombuffer()
创建一个引用字节缓冲区中像素数据的图像内存。
请注意,此函数仅解码像素数据,而不是整个图像。如果您在字符串中有整个图像文件,请将其包装在 BytesIO 对象中,然后使用 open() 加载它。
Syntax: PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args)
Parameters:
mode – The image mode. See: Modes
size – The image size.
data – A byte buffer containing raw data for the given mode.
decoder_name – What decoder to use.
args – Additional parameters for the given decoder. For the default encoder (“raw”), it’s recommended that you provide the full set of parameters:frombuffer(mode, size, data, "raw", mode, 0, 1)
Returns: An Image object.
使用的图像:
# importing image object from PIL
from PIL import Image
# creating an image object
im = Image.open(r"C:\Users\System-Pc\Desktop\rose.jpg")
im1 = im.tobytes("xbm", "rgb")
img = Image.frombuffer("L", (4, 4), im1, 'raw', "L", 0, 1)
# creating list
img2 = list(img.getdata())
print(img2)
输出:
[48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48, 120, 102, 102, 44, 48]
另一个例子:这里我们使用另一个图像。
使用的图像:
# importing image object from PIL
from PIL import Image
# creating an image object
im = Image.open(r"C:\Users\System-Pc\Desktop\ellipse1.png")
im1 = im.tobytes("xbm", "rgb")
img = Image.frombuffer("L", (10, 10), im1, 'raw', "L", 0, 1)
# creating list
img2 = list(img.getdata())
print(img2)
输出:
[48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 10, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56, 44, 48, 120, 56, 56]