Home > Enterprise >  error in convert binary value in txt file to image
error in convert binary value in txt file to image

Time:10-25

I have file have some value like this "01100000,10101000,01101000,01110000,10101100,01110000,01101000,10101 " this is the value of JPEG image (120*160)and I need to convert this file to image, I'm trying with this code but I have this error!

pixels[x,y] = diff(i2) #Creates a black image. What do? TypeError: color must be int or tuple

with open("C://Users//kk//Desktop//rbb8bin.txt") as file:
    vdiv = [line.strip() for line in file]
print(vdiv)

def diff(inp):
    if inp == '1':
        return (0,0,0)
    if inp == '0':
        return (255,255,255)
    else:
        pass
img = Image.new( 'RGB', (8,len(vdiv)), "white")
pixels = img.load()

for x in range(img.size[0]):
    for y in range(img.size[1]):
        for i in vdiv:
            for i2 in i:
                pixels[x,y] = diff(i2) #Creates a black image. What do?

img.show()

CodePudding user response:

You really need to differentiate between ASCII text and binary files. Your file is stored in a very ugly, inefficient way. Here's one (equally ugly) way of making it back into a JPEG:

#!/usr/bin/env python3

import csv

# Read text file as CSV into list
with open('data') as f:
    reader = csv.reader(f)
    # Discard height and width, i.e. first two values
    data = list(reader)[0][2:]

# Open binary output file, convert each string to bytes and write
with open('image.jpg', 'wb') as out:
    for v in data:
        b = int(v,2).to_bytes(1,byteorder='big')
        out.write(b)

enter image description here

  • Related