Convert an integer array to a PNG image in Python

2019-08-28 03:05发布

I've been trying to convert an integer array of RGB values to a PNG image. How can I generate the following image from the following integer array?

enter image description here

'''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]],
]

标签: python png
2条回答
Summer. ? 凉城
2楼-- · 2019-08-28 03:24

You can use the Python Imaging Library to convert RGB datapoints to most standard formats.

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 output

The .save() method can also take a format argument, PNG would fix the output to PNG.

(I recommend you install the Pillow fork as it is more actively maintained and adds proper packaging and Python 3 support).

查看更多
ら.Afraid
3楼-- · 2019-08-28 03:26

The Python Imaging Library (PIL) is handy for most imaging needs in Python. The Image module contains a fromstring function and a save function that should do exactly what you're looking for.

查看更多
登录 后发表回答