4

Forgive me for any naivety, but I am new to working with images. Say I have a list of binary values [1,0,0,0,1,0,1,0,0,0,0,1,1,0....] which represent pixels in a black and white image. How would I go about making a .png file from this list?

3
  • Is this just a 1-D list? Commented Apr 15, 2011 at 5:40
  • Yes, it's just a 1-D list, but I want to make a 5x5 image and do want to map 0 to pure black and 1 to pure white. I can't figure out how to work with BasicWolf's suggestion, it creates an image, but the image is all black. Commented Apr 15, 2011 at 16:26
  • 1
    Actually it's mostly black. If you take his suggestion, you'll be writing 0 and 1, which out of 255 will look pretty darn black. Commented Apr 15, 2011 at 16:37

2 Answers 2

4

Use Python Imaging Library for this purpose.

There is a img = Image.frombuffer(mode, size, data) method which creates an image from "raw" data (a string). You can then save it as PNG file via img.save('image.png', transparency=transparency)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes but he wants to map 0 to pure black (0,0,0) and 1 to pure white (255,255,255)
3

Expanding on BasicWolf's example:

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're after...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.