How to convert hex string to color image in python

2019-08-02 12:29发布

i'm new in programming so i have some question about converting string to color image.

i have one data , it consists of Hex String, like a fff2f3..... i want to convert this file to png like this.

enter image description here

i can convert the hex data to png image through this site but i don't know how to convert the hex data to png image using python code but i tried to use Image.frombytes('RGB',(1600,1059),hex_str) but i don't know image size , so i cannot use this method.

so My question is how can i convert this hex data to image using python code

please give me some advise , thank you :)

1条回答
在下西门庆
2楼-- · 2019-08-02 12:39

Reading the hexadecimal string into a bytes object, and then writing that binary into a .png file can be done like this:

with open('binary_file') as file:
    data = file.read()

data = bytes.fromhex(data[2:])

with open('image.png', 'wb') as file:
    file.write(data)

And produces this result, keep in mind it is corrupted:

corrupted result

查看更多
登录 后发表回答