-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_steganography.py
More file actions
88 lines (68 loc) · 2.66 KB
/
image_steganography.py
File metadata and controls
88 lines (68 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# python image_steganography.py encode input_image.png "Hello, World!" output_image.png
# python image_steganography.py decode output_image.png
from PIL import Image
import sys
def encode_image(image_path, message, output_path):
img = Image.open(image_path)
if img.mode != 'RGB':
raise ValueError("The image should be in RGB mode")
binary_message = ''.join(format(ord(char), '08b') for char in message) + '1111111111111110'
img_data = img.getdata()
new_img_data = []
message_index = 0
for pixel in img_data:
pixel = list(pixel)
for i in range(3):
if message_index < len(binary_message):
pixel[i] = (pixel[i] & ~1) | int(binary_message[message_index])
message_index += 1
new_img_data.append(tuple(pixel))
new_img = Image.new(img.mode, img.size)
new_img.putdata(new_img_data)
new_img.save(output_path)
print(f"Message hidden successfully! Output image saved as {output_path}")
def decode_image(image_path):
img = Image.open(image_path)
if img.mode != 'RGB':
raise ValueError("The image should be in RGB mode")
img_data = img.getdata()
binary_message = []
for pixel in img_data:
for i in range(3):
binary_message.append(str(pixel[i] & 1))
binary_message = ''.join(binary_message)
end_index = binary_message.find('1111111111111110')
if end_index != -1:
binary_message = binary_message[:end_index]
else:
print("No hidden message found!")
return ""
message = ''.join(chr(int(binary_message[i:i+8], 2)) for i in range(0, len(binary_message), 8))
return message
def main():
if len(sys.argv) < 3:
print("Usage: python image_steganography.py encode <image_path> <message> <output_path>")
print("or")
print("Usage: python image_steganography.py decode <image_path>")
sys.exit(1)
operation = sys.argv[1]
if operation == 'encode':
if len(sys.argv) != 5:
print("Usage: python image_steganography.py encode <image_path> <message> <output_path>")
sys.exit(1)
image_path = sys.argv[2]
message = sys.argv[3]
output_path = sys.argv[4]
encode_image(image_path, message, output_path)
elif operation == 'decode':
if len(sys.argv) != 3:
print("Usage: python image_steganography.py decode <image_path>")
sys.exit(1)
image_path = sys.argv[2]
message = decode_image(image_path)
print(f"Hidden message: {message}")
else:
print("Invalid operation! Use 'encode' or 'decode'.")
sys.exit(1)
if __name__ == "__main__":
main()