'How I can convert a list of integers to an image?

I converted an image to a list of integers. E.g. [226, 137, 125, 226, 137, 125, 223, 137, 133, 223, 136, 128, 226, 138, 120, 226, 129, 116, 228, 138, 123, 227, 134, 124, 227, 140, 127, 225, 136, 119, 228, 135, 126, 225, 134, 121, 223, 130, 108, 226, 139, 119, 223, 135, 120, 221, 129, 114, 221, 134, 108, 221, 131, 113, 222, 138, 121, 222, 139, 114, 223, 127, 109, 223, 132, 105, 224, 129, 102, 221, 134, 109, 218, 131, 110, 221, 133, 113, 223, 130, 108, 225, 125, 98, 221, 130, 121, 221, 129, 111, 220, 127, 121, 223, 131, 109, 225, 127, 103, 223] How I can reverse this process and recover my image. I used PIL library and python 3.6.



Solution 1:[1]

You can use PIL and numPy. Try the code as given below.

from PIL import Image
import numpy as np


pixels =[226, 137, 125, 226, 137, 125, 223, 137, 133, 223, 136, 128, 226, 138, 120, 226, 129, 116, 228, 138, 123, 227, 134, 124, 227, 140, 127, 225, 136, 119, 228, 135, 126, 225, 134, 121, 223, 130, 108, 226, 139, 119, 223, 135, 120, 221, 129, 114, 221, 134, 108, 221, 131, 113, 222, 138, 121, 222, 139, 114, 223, 127, 109, 223, 132, 105, 224, 129, 102, 221, 134, 109, 218, 131, 110, 221, 133, 113, 223, 130, 108, 225, 125, 98, 221, 130, 121, 221, 129, 111, 220, 127, 121, 223, 131, 109, 225, 127, 103, 223] 

# Convert the pixels into an array using numpy
array = np.array(pixels, dtype=np.uint8)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array)
new_image.save('new.png')

Or

image_out = Image.new(image.mode,image.size)
image_out.putdata(pixels)


image_out.save('test_out.png')

Solution 2:[2]

calling list on bytes gives you a list of integers.

some_bytes = b'\xbe\xbf\xc0'

list(some_bytes)

[190, 191, 192]

calling bytes on a list of integers gives you bytes.

bytes([190,191,192])

b'\xbe\xbf\xc0'

read an image into a list of integers:

>>>> with open("acme.png","rb") as ifile:
....     a_list= list(ifile.read())
....     

write that list of integers to a new image file

>>>> with open("acme2.png","wb+") as ofile:
....     ofile.write(bytes(a_list))

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
Solution 2