简体   繁体   中英

Python: Save a hex string to a jpg image file

I have multiple hex strings like this one (big string so I truncated the middle):

0xFFD8FFEE000E41646F626500640000000002FFE11E2445786966000049492A006A0500002C010000010000002C0100000100000041646F62652050686F746F73686F702043533620284D6163................................................................................................................................................................7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3FF7F8F9FAFFC4001F0100030101010101010101010000000000000102030405060708090A0BFFC400B511000201020404030407050404000102770

I want to save each string in a file. But my code is not working well:

import binascii

data = binascii.a2b_hex(my_hex_string)
with open('/path/image.jpg', 'wb') as image_file:
    image_file.write(data)

I receive this error:

TypeError: Odd-length string

When I remove the first 0 I get this:

TypeError: Non-hexadecimal digit found

When I remove the two first chars (since JPG is supposed to start with FF D8), I get this again:

TypeError: Odd-length string

Any ideas please?

Are you sure the string doesn't have something extra in it? Whitespace, newlines, etc?

Try my_hex_string.strip()

Also, there is possibility, you can have spaces inside the string, so you can do something like that to clean them out:

binascii.a2b_hex(toSend.replace(' ', ''))

3.5 yo thread. But is getting many views, so I will add my 2c. OP's code works just fine for me. My guess is that the hex string is corrupted. Most prominantly, not seeing an FFD9 for "end of image."

I had the same problem and I tested your code. I think there is nothing wrong with your code. Just try to remove the 0x from the beginning of your Hex Codes. I think that would work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM