Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hack-r/40fe6d24c6be47ee59ef5a7e5dc178d8 to your computer and use it in GitHub Desktop.
Save hack-r/40fe6d24c6be47ee59ef5a7e5dc178d8 to your computer and use it in GitHub Desktop.
from PIL import Image
def hide_text_in_image(image_path, text):
image = Image.open(image_path)
pixels = list(image.getdata())
# Convert text to binary
binary_text = ''.join(format(ord(char), '08b') for char in text)
if len(binary_text) > len(pixels):
raise ValueError("Text too long to hide in the image")
encoded_pixels = []
index = 0
for pixel in pixels:
if index < len(binary_text):
# Hide one bit of the text in the least significant bit of each color channel
red = pixel[0] & 0b11111110 | int(binary_text[index])
green = pixel[1] & 0b11111110 | int(binary_text[index])
blue = pixel[2] & 0b11111110 | int(binary_text[index])
encoded_pixels.append((red, green, blue))
index += 1
else:
encoded_pixels.append(pixel)
encoded_image = Image.new(image.mode, image.size)
encoded_image.putdata(encoded_pixels)
# Save the encoded image with a different filename
encoded_image.save("encoded_image.png")
print("Text hidden successfully in the image.")
def extract_text_from_image(image_path):
encoded_image = Image.open(image_path)
encoded_pixels = list(encoded_image.getdata())
extracted_text = ""
for pixel in encoded_pixels:
# Extract the least significant bit of each color channel
red = pixel[0] & 0b00000001
green = pixel[1] & 0b00000001
blue = pixel[2] & 0b00000001
extracted_text += str(red)
extracted_text += str(green)
extracted_text += str(blue)
# Convert binary to text
text = ""
for i in range(0, len(extracted_text), 8):
char = extracted_text[i:i+8]
text += chr(int(char, 2))
return text
# Example usage:
image_path = "original_image.png"
text_to_hide = "This is a secret message!"
hide_text_in_image(image_path, text_to_hide)
# Extract the hidden text from the encoded image
extracted_text = extract_text_from_image("encoded_image.png")
print("Extracted text:", extracted_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment