迭代十六进制以创建jpeg文件

时间:2017-09-15 08:18:26

标签: python image hex

我有一个十六进制行的文本文件。我希望每一行都转换为jpeg.file,因为它们是照片。我可以像这样单独使用binascii.a2b_hex(我缩短了十六进制):

data = binascii.a2b_hex("FFD8FFE")
with open('image.jpg', 'wb') as image_file:
    #image_file.write(data)

现在我想批量生产。所以我有一个十六进制行的文本文件,我希望每个十六进制都写入他自己的jpeg文件。我想我差不多了,但是我的代码给了我这个错误:

ValueError: too many values to unpack

以下是代码:

import binascii
text_file = open("photos-clean.txt", "w")

#for each hexadecimal, put it in between single quotes so it becomes a string. Also remove the first two chars from a line.
with open('photos.txt', 'r') as f:
    for i in f:
        photo = i[2:]
        quotes = "'" + photo.rstrip() + "'"
        print quotes
        text_file.write(quotes)
        text_file.write("\n")

text_file.close()

#for each hexadecimal, transform it to a jpeg with binascii and write it to his own jpeg.file
with open("photos-clean.txt", "r") as f2:
    for i, data in (f2):
        transform = binascii.a2b_hex(i)
        with open('photo{}.jpg'.format(transform), 'wb') as output:
            output.write(data)

编辑:我有答案,这就是我应该做的:

import binascii
text_file = open("photos-clean.txt", "w")


with open('photos.txt', 'r') as f:
    for i in f:
        photo = i[2:]
        text_file.write(photo)
        text_file.write("\n")

text_file.close()


with open("photos-clean.txt", "r") as f2:
    count=0
    for i in f2:
        count = count + 1
        cleaned = i.strip("\r\n")
        transform = binascii.a2b_hex(cleaned)
        with open("{}.jpg".format(count), 'wb') as output:
            output.write(transform)

1 个答案:

答案 0 :(得分:0)

我猜您在第for i, data in (f2):行有错误。 你试图从f2解包2值i和数据,我想你需要枚举如下。 此外,我假设您想使用i作为文件名的索引,并将转换而不是数据写入输出

with open("photos-clean.txt", "r") as f2:
    for i, data in enumerate(f2):
        transform = binascii.a2b_hex(data)
        with open('photo{}.jpg'.format(i), 'wb') as output:
            output.write(transfrom)