Binary list for PNG in Python

Forgive me for any naivety, but I'm new to working with images. Say I have a list of binary values ​​[1,0,0,0,1,0,1,0,0,0,0,0,0,1,1,0 ....] that represent pixels in a black and white image How can I make a .png file from this list?

+4
source share
2 answers

To do this, use the Python image library.

There is a method img = Image.frombuffer(mode, size, data) that creates an image from raw data (rows). Then you can save it as a PNG file using img.save('image.png', transparency=transparency)

+4
source

Extension on the example of BasicWolf:

 from PIL import Image import struct size = 5, 5 arr = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0] data = struct.pack('B'*len(arr), *[pixel*255 for pixel in arr]) img = Image.frombuffer('L', size, data) img.save('image.png') 

I think this is what you need ...

+3
source

All Articles