Reputation: 31840
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?
'''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]],
]
Upvotes: 0
Views: 7328
Reputation: 1123440
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:
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).
Upvotes: 7
Reputation: 308402
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.
Upvotes: 1