在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)
通过以上代码,可以实现图像的隐藏和信息提取的功能。需要注意的是,隐藏的信息不要太长,以免影响图像的质量。