Python程序图片的嵌入和提取
时间: 2024-10-22 18:05:59 浏览: 13
在Python中,可以使用多种库来进行图片的数字水印嵌入和提取,比如`PIL`(Pillow)库。以下是基于LSB(Least Significant Bit)技术的一个简单示例:
**图片嵌入(Embedding)**:
```python
from PIL import Image
def embed_watermark(image_path, watermark_text):
img = Image.open(image_path)
binary_watermark = ''.join(format(ord(c), '08b') for c in watermark_text)
for y in range(img.height):
for x in range(img.width):
pixel = img.getpixel((x, y))
new_pixel = list(pixel)
# 取LSB
bit = int(new_pixel[-1])
# 替换LSB为新的比特值
if binary_watermark:
new_bit = 1 if bit ^ int(binary_watermark[0]) else bit
binary_watermark = binary_watermark[1:]
new_pixel[-1] = str(new_bit)
img.putpixel((x, y), tuple(new_pixel))
# 保存嵌入水印的图片
embedded_img_path = "embedded_" + image_path
img.save(embedded_img_path)
# 使用示例
embed_watermark("original.jpg", "Hello World!")
```
**图片提取(Extraction)**:
```python
def extract_watermark(embedded_image_path):
img = Image.open(embedded_image_path)
binary_data = ""
for y in range(img.height):
for x in range(img.width):
pixel = img.getpixel((x, y))
bit = int(pixel[-1])
binary_data += str(bit)
return binary_data
# 使用示例
extracted_data = extract_watermark("embedded_original.jpg")
```
请注意这只是一个基本示例,实际应用中需要考虑更多细节,比如错误检测和纠正、保密性和鲁棒性等。
阅读全文