I was trying to create an example of stegnography techniques in python by creating a program that converts an image to its binary with the python PIL module. Once converted it would strip the least significant bit from each pixel value and change it to encode a message across a certain number of bytes; it would do this whilst (theoretically) keeping the approximate size of the file and maintaining most of the image's appearance.
I have however, run into a problem whereby I cannot reconstruct the image or any image at all for that matter using the data I am left with.
#secret message to be injected into the final bits.
injection = '0111001101100101011000110111001001100101011101000010000001101101011001010111001101110011011000010110011101100101001000000110100101101110011010100110010101100011011101000110100101101111011011100010000001101101011011110110110101100101011011100111010000100000011010000110010101101000011001010110100001100101011010000110010101101000011001010110100001100101'
injection_array=[]
count = 0
#loop to create an array of characters for the injection
for char in injection:
injection_array.append(injection[count])
count += 1
injectioncount = 0
count = 0
#loop to replace each bit with the desired injection
for element in pixel_bin:
cached_element = pixel_bin[count]
lsb_strip = cached_element[:-1]
lsb_replace = lsb_strip + injection_array[injectioncount]
pixel_bin[count] = lsb_replace
count += 1
injectioncount += 1
if injectioncount == len(injection):
break
#dumps outputted value for comparison with a control file of original pixel values
with open("comparison.json","w") as f:
json.dump(pixel_bin,f, indent=2)
And this is as far as I have managed to get. The output from this is a list containing varying sequences of binary with the final bit changed.
This is how I am getting the pixel data in the first place:
def bincon(image):
from PIL import Image
count = 0
pixel_binaries = []
im = Image.open(image, 'r')
pix_val = list(im.getdata()) #outputs rgb tuples for every pixel
pix_val_flat = [x for sets in pix_val for x in sets] #flattens the list so that each list item is just one rgb value
for elements in pix_val_flat: #converts each rgb value into binary
pixel_binaries.append(bin(pix_val_flat[count]))
count += 1
return pixel_binaries
How would I go about reconstructing the data I have gathered into something resembling the image I have input into the program?
EDIT - trying the im_out = Image.fromarray(array_data_is_stored_in) method does return an image file which opens but contains no data, certainly not the original image.

im_out = Image.fromarray(array_data_is_stored_in)if your data is stored in the appropriately shaped 2D array. They might have to be Numpy arrays as well.for element in pixel_bin:, but then you don’t useelementin the loop body. You also don’t definepixel_binanywhere. I recommend that you use a NumPy array to represent your image, and use NumPy operations on it. Finally, what is the value of'0'? Is it 0 or is it 48?