在Python中,可以使用Pillow庫來實現圖像的隱寫術與信息提取。
from PIL import Image
def hide_text_in_image(image_path, text):
img = Image.open(image_path)
width, height = img.size
binary_text = ''.join(format(ord(char), '08b') for char in text)
index = 0
for x in range(width):
for y in range(height):
pixel = list(img.getpixel((x, y)))
for i in range(3):
if index < len(binary_text):
pixel[i] = pixel[i] & 254 | int(binary_text[index])
index += 1
img.putpixel((x, y), tuple(pixel))
img.save("hidden_image.png")
hide_text_in_image("image.jpg", "Hello, this is a hidden message")
from PIL import Image
def extract_text_from_image(image_path):
img = Image.open(image_path)
width, height = img.size
binary_text = ""
for x in range(width):
for y in range(height):
pixel = img.getpixel((x, y))
for i in range(3):
binary_text += str(pixel[i] & 1)
text = ""
for i in range(0, len(binary_text), 8):
byte = binary_text[i:i+8]
text += chr(int(byte, 2))
if text[-5:] == "#####":
break
return text[:-5]
hidden_text = extract_text_from_image("hidden_image.png")
print(hidden_text)
通過以上代碼,可以實現圖像的隱藏和信息提取的功能。需要注意的是,隱藏的信息不要太長,以免影響圖像的質量。