简体   繁体   English

在Python中将整数数组转换为PNG图像

[英]Convert an integer array to a PNG image in Python

I've been trying to convert an integer array of RGB values to a PNG image. 我一直在尝试将RGB值的整数数组转换为PNG图像。 How can I generate the following image from the following integer array? 如何从下面的整数数组生成下面的图像?

在此处输入图片说明

'''This is a 3D integer array. Each 1D array inside this array is an RGBA value'''
'''Now how can I convert this RGB array to the PNG image shown above?'''
rgbArray = [
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[255,0,0], [255, 0, 0], [255, 0, 0], [255, 0, 0], [0,0,255], [0,0,255], [0,0,255], [0,0,255]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
[[0,0,255], [0,0,255], [0,0,255], [0,0,255], [255, 0, 0], [255, 0, 0], [255, 0, 0], [255, 0, 0]],
]

You can use the Python Imaging Library to convert RGB datapoints to most standard formats. 您可以使用Python Imaging Library将RGB数据点转换为大多数标准格式。

from PIL import Image

newimage = Image.new('RGB', (len(rgbArray[0]), len(rgbArray)))  # type, size
newimage.putdata([tuple(p) for row in rgbArray for p in row])
newimage.save("filename.png")  # takes type from filename extension

which produces: 产生: PIL输出

The .save() method can also take a format argument, PNG would fix the output to PNG. .save()方法也可以采用format参数, PNG会将输出固定为PNG。

(I recommend you install the Pillow fork as it is more actively maintained and adds proper packaging and Python 3 support). (我建议您安装Pillow叉子,因为它会得到更积极的维护,并增加了适当的包装和Python 3支持)。

The Python Imaging Library (PIL) is handy for most imaging needs in Python. Python映像库(PIL)可满足大多数Python映像需求。 The Image module contains a fromstring function and a save function that should do exactly what you're looking for. Image模块包含一个fromstring函数和一个save函数,它们应该可以完全满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM