Hide files in image pixels (steganography)
Method: Use steganography to hide files inside image pixels.
from PIL import Image
# Function to hide a file within an image
def hide_file(image_path, file_to_hide, output_image_path):
# Open the image
image = Image.open(image_path)
# Open the file to hide
with open(file_to_hide, “rb”) as file:
data_to_hide = file.read()
# Convert data to a list of bits
binary_data = [format(byte, ’08b’) for byte in data_to_hide]
# Embed the data into the image’s LSBs
pixel_data = list(image.getdata())
pixel_index = 0
for i in range(len(binary_data)):
pixel = list(pixel_data[pixel_index])
for j in range(3): # Process the RGB channels
pixel[j] = int(format(pixel[j], ’08b’)[:-1] + binary_data[i][j], 2)
i += 1
if i == len(binary_data):
break
pixel_data[pixel_index] = tuple(pixel)
pixel_index += 1
# Create a new image with the hidden data
hidden_image = Image.new(image.mode, image.size)
hidden_image.putdata(pixel_data)
# Save the image with hidden data
hidden_image.save(output_image_path)
print(f”File ‘{file_to_hide}’ hidden within ‘{image_path}’ and saved as ‘{output_image_path}’.”)
# Function to extract a hidden file from an image
def extract_hidden_file(image_path, output_file):
# Open the image
image = Image.open(image_path)
# Extract LSBs from the image pixels and convert to bytes
binary_data = “”
pixel_data = list(image.getdata())
for pixel in pixel_data:
for channel in pixel:
binary_data += format(channel, ’08b’)[-1]
# Convert binary data to bytes
extracted_data = bytes(int(binary_data[i:i+8], 2) for i in range(0, len(binary_data), 8))
# Write the extracted data to the output file
with open(output_file, “wb”) as file:
file.write(extracted_data)
print(f”Hidden file extracted and saved as ‘{output_file}’.”)
# Example usage
if name == “main”:
# Hide a file within an image
hide_file(“image.png”, “file_to_hide.txt”, “output_image_with_hidden_data.png”)
# Extract the hidden file from the image
extract_hidden_file(“output_image_with_hidden_data.png”, “extracted_hidden_file.txt”)
In this example we use the Pillow library to manipulate the image. The hide_file function hides data inside an image, and the extract_hidden_file function extracts hidden data.
Make sure the required image files and the files to hide are in the same directory and replace “image.png” with “file_to_hide.txt” filenames.”output_image_with_hidden_data.png””extracted_hidden_file.txt”
