'How do python Pil getdata() to hex fast?

  fil="IMG1.JPG"
  im = Image.open(fil) 
  pixels=list(im.getdata())
  hex_list=[]
  for px in pixels:
    he='%02x%02x%02x' % px
    hex_list.append(he)

The code works but when the images are large is too slow, it is not possible faster? it is possible to getdata() directly in hex?

Thank you for interest? Good works.



Solution 1:[1]

To convert the raw image to a hex string, get the bytes using tobytes() and then convert to hex with the binascii module.

import binascii

im_bytes = im.tobytes()
im_hex = binascii.hexlify(im_bytes)

To convert it to a compressed format (JPG, PNG) in a hex string:

import binascii
import io

im_bytes = io.BytesIO()
im.save(im_bytes, format='JPEG')
im_hex = binascii.hexlify(im_bytes.getvalue())

Solution 2:[2]

Read in a jpg and make a string of hex values. Then reverse the procedure. Take a string of hex and write it out as a jpg file...

import binascii

with open('my_img.jpg', 'rb') as f:
    data = f.read()
    
im_hex = binascii.hexlify(data)

# check out the hex...
print(im_hex[:10])

# reversing the procedure
im_hex = binascii.a2b_hex(im_hex)
print(im_hex[:10])

# write it back out to a jpg file
with open('my_hex.jpg', 'wb') as image_file:
    image_file.write(im_hex)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xli
Solution 2