5

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 :)

Soulduck
  • 569
  • 1
  • 6
  • 17
  • How many pixels are in the data? Knowing the number of pixels might help figuring out the heighth and width ... `H * W == number_of_pixels`. – wwii Jul 16 '18 at 02:46
  • If there are 65536 characters in the string and the image is `'RGBA'` then there are 8 characters per pixel which would be 8192 pixels - so maybe the image size is 128x64 or 256x32 ... – wwii Jul 16 '18 at 02:56
  • Why don't you know the image size? – Ignacio Vazquez-Abrams Jul 16 '18 at 03:09
  • @wwii thanks for comment, I don't think ,the image size is 128x64 or 256x32 , becuase when i recover image from string using the web program that i mentioned above, the image size is 600 x 1590, so my question is how web program that convert string to image can know image size , even my string file is broken , thank you – Soulduck Jul 17 '18 at 04:37
  • @IgnacioVazquez-Abrams thank you for comments , because i just have string file and my files almost broken , so i don't know the image size exactly, – Soulduck Jul 17 '18 at 04:39

1 Answers1

8

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

Alistair Carscadden
  • 1,198
  • 5
  • 18
  • I know this old, but I just wanted to add that `.strip()` fixed my ended issue. I was importing text from a text editor that enjoyed making subtle changes to the raw file, including an extra \n at end (Atom editor). – Jack Hales Apr 27 '21 at 04:00
  • @Alistair: Does this work the same way in C? – coder101 May 18 '21 at 20:59
  • @coder101 Yes, there is nothing language specific about the solution. It will have to be translated, of course. – Alistair Carscadden May 18 '21 at 22:05