Search code examples
pythonimageeeprom

How do I write to a binary file using pixel data from the function "image" the Python Image Library?


I cannot figure out how to do what Ben Eater did.

I have the exact same code (different file name) but the error I get is that I cannot use the argument pixels[x,y] for chr() to write to a binary file

The video I linked has all the information of what I am trying to accomplish. If you have a specific question for me, ask away. btw...I have literally been trying to make this work about a year and have not figured out how to do it so...yeah.

'''

from PIL import Image

image = Image.open("Margarita3.png")
pixels = image.load()

out_file = open("Margarita3.bin", "wb")

for y in range(150):
  for x in range(200):
    try:
      out_file.write(chr(pixels[x, y]))
    except IndexError:
      out_file.write(chr(0))

'''

here is the error message

    Traceback (most recent call last):
      File "C:\Users\Nicky\Desktop\tolaptop\wincupl_vga_timings\convert.py", line 
    11, in <module>
        out_file.write(chr(pixels[x,y]))
    TypeError: an integer is required

Solution

  • Make sure the image is in the correct location. According to your current code, it should be in the same directory as the python script. If you want to specify otherwise, you should do it like so:

    image = Image.open("C:\Users\Nicky\Desktop\tolaptop\...Margarita3.png")
    pixels = image.load()
    
    out_file = open("C:\Users\Nicky\Desktop\tolaptop\...Margarita3.bin", "wb")