Skip to content

Instantly share code, notes, and snippets.

@anmolj7
Created December 5, 2019 14:37
Show Gist options
  • Save anmolj7/fc5bbafa66adf09cb4f8f83c1d7a47f9 to your computer and use it in GitHub Desktop.
Save anmolj7/fc5bbafa66adf09cb4f8f83c1d7a47f9 to your computer and use it in GitHub Desktop.
from PIL import Image
def gen_data(data):
new_data = []
for i in data:
new_data.append(format(ord(i), '08b'))
return new_data
def mod_pix(pix, data):
data_list = gen_data(data)
data_len = len(data_list)
im_data = iter(pix)
for i in range(data_len):
pix = [value for value in im_data.__next__()[:3] +
im_data.__next__()[:3] +
im_data.__next__()[:3]]
for j in range(0, 8):
if (data_list[i][j]=='0') and (pix[j]% 2 != 0):
if (pix[j]% 2 != 0):
pix[j] -= 1
elif (data_list[i][j] == '1') and (pix[j] % 2 == 0):
pix[j] -= 1
if (i == data_len - 1):
if (pix[-1] % 2 == 0):
pix[-1] -= 1
else:
if (pix[-1] % 2 != 0):
pix[-1] -= 1
pix = tuple(pix)
yield pix[0:3]
yield pix[3:6]
yield pix[6:9]
def encode_enc(new_img, data):
w = new_img.size[0]
(x, y) = (0, 0)
for pixel in mod_pix(new_img.getdata(), data):
new_img.putpixel((x, y), pixel)
if (x == w - 1):
x = 0
y += 1
else:
x += 1
def encode():
img = input("Enter image name(with extension): ")
image = Image.open(img, 'r')
data = input("Enter data to be encoded : ")
if (len(data) == 0):
raise ValueError('Data is empty')
new_img = image.copy()
encode_enc(new_img, data)
new_img_name = input("Enter the name of new image(with extension): ")
new_img.save(new_img_name, str(new_img_name.split(".")[1].upper()))
def decode():
img = input("Enter image name(with extension) :")
image = Image.open(img, 'r')
data = ''
img_data = iter(image.getdata())
while (True):
pixels = [value for value in img_data.__next__()[:3]+img_data.__next__()[:3] +img_data.__next__()[:3]]
binstr = ''
for i in pixels[:8]:
if (i % 2 == 0):
binstr += '0'
else:
binstr += '1'
data += chr(int(binstr, 2))
if (pixels[-1] % 2 != 0):
return data
# Main Function
def main():
a = int(input("1. Encode\n2. Decode\nYour Choice: "))
if (a == 1):
encode()
elif (a == 2):
print("Decoded word- " + decode())
else:
raise Exception("Enter correct input")
if __name__ == '__main__' :
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment