lsb隐写 python
时间: 2023-06-21 11:19:19 浏览: 124
LSB隐写是一种基于最低有效位(Least Significant Bit)的隐写术,可以将秘密信息隐藏在图像、音频或视频等媒体文件中。在Python中,可以使用Pillow库来实现LSB隐写。以下是一个简单的LSB隐写示例代码:
```python
from PIL import Image
def encode_lsb(image_path, secret_message):
img = Image.open(image_path)
pixels = img.load()
width, height = img.size
bit_message = ''.join(format(ord(c), '08b') for c in secret_message) + '11111111'
index = 0
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
if index < len(bit_message):
pixels[x, y] = (r & 254 | int(bit_message[index]), g, b)
index += 1
img.save('encoded.png')
def decode_lsb(image_path):
img = Image.open(image_path)
pixels = img.load()
width, height = img.size
bit_message = ''
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
bit_message += str(r & 1)
secret_message = ''
for i in range(0, len(bit_message), 8):
if bit_message[i:i+8] == '11111111':
break
else:
secret_message += chr(int(bit_message[i:i+8], 2))
return secret_message
```
其中,encode_lsb函数用于将秘密信息编码到图片中,decode_lsb函数用于从图片中解码出秘密信息。注意,在编码时需要在秘密信息末尾添加一个8位的结束标志。
阅读全文