This is my code for encoding and decoding. However it didn't give me the expected results when I tried to decode the stago.jpg online.
I got this result from online decoder: ¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶Ûm¶...
from PIL import Image
import os
Encoding Code:
# Encoding
def encode_text_to_image(cover_image_path, payload_text, output_image_path, numLSB):
cover_image = Image.open(cover_image_path)
width, height = cover_image.size
# Convert the payload text to binary
payload_bytes = payload_text.encode('utf-8')
payload_length = len(payload_bytes)
# Ensure that the payload can fit within the cover image
max_payload_length = (width * height * 3 * numLSB) // 8
if payload_length > max_payload_length:
raise ValueError("Payload text is too large for the cover image")
# Add payload length metadata to the binary payload
binary_payload = format(payload_length, '032b')
# Iterate over each pixel in the cover image
index = 0
for y in range(height):
for x in range(width):
if index < len(binary_payload):
# Get the RGB values of the current pixel
r, g, b = cover_image.getpixel((x, y))
# Modify the least significant bits of each RGB value
for i in range(numLSB):
mask = 1 << i
if index < len(binary_payload):
r = (r & ~mask) | (int(binary_payload[index]) << i)
index += 1
# Set the modified RGB values in the cover image
cover_image.putpixel((x, y), (r, g, b))
elif index - len(binary_payload) < payload_length * 8:
# Get the RGB values of the current pixel
r, g, b = cover_image.getpixel((x, y))
# Modify the least significant bits of each RGB value using payload bytes
for i in range(numLSB):
mask = 1 << i
if index - len(binary_payload) < payload_length * 8:
byte_index = (index - len(binary_payload)) // 8
bit_index = (index - len(binary_payload)) % 8
payload_byte = payload_bytes[byte_index]
payload_bit = (payload_byte >> (7 - bit_index)) & 1
r = (r & ~mask) | (payload_bit << i)
index += 1
# Set the modified RGB values in the cover image
cover_image.putpixel((x, y), (r, g, b))
# Save the steganographic image
cover_image.save(output_image_path)