-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLSB_encode.py
More file actions
42 lines (32 loc) · 1.33 KB
/
LSB_encode.py
File metadata and controls
42 lines (32 loc) · 1.33 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
from PIL import Image
def embed_lsb_optimized(image_path, message, output_path, num_bits=1):
img = Image.open(image_path).convert('RGB')
width, height = img.size
pixels = img.load()
binary_message = ''.join(format(ord(c), '08b') for c in message + '\x00')
if len(binary_message) > width * height * 3 * num_bits:
raise ValueError("Message is too long!")
bit_index = 0
mask = 0xFF & ~((1 << num_bits) - 1)
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
channels = [r, g, b]
for i in range(3):
if bit_index < len(binary_message):
chunk = binary_message[bit_index:bit_index + num_bits]
chunk = chunk.ljust(num_bits, '0')
val = int(chunk, 2)
channels[i] = (channels[i] & mask) | val
bit_index += num_bits
pixels[x, y] = tuple(channels)
if bit_index >= len(binary_message):
img.save(output_path)
return print("Ready!!")
img.save(output_path)
embed_lsb_optimized(
image_path="input.png", # input image
message="SecretMessage",
output_path="output.png",
num_bits=1 # bits (lower is more inconspicuously)
)