写一段利用异或逻辑运算符加密图片的代码。(加密和解密都要写
时间: 2024-05-05 10:15:56 浏览: 140
加密代码:
```python
from PIL import Image
def encrypt_image(filename, key):
# 打开图片并获取像素矩阵
img = Image.open(filename)
pixels = img.load()
# 循环遍历每个像素点,对 RGB 三个通道进行异或运算
width, height = img.size
for x in range(width):
for y in range(height):
r, g, b = pixels[x, y]
r ^= key
g ^= key
b ^= key
pixels[x, y] = (r, g, b)
# 保存加密后的图片
img.save('encrypted.png')
```
解密代码:
```python
from PIL import Image
def decrypt_image(filename, key):
# 打开图片并获取像素矩阵
img = Image.open(filename)
pixels = img.load()
# 循环遍历每个像素点,对 RGB 三个通道进行异或运算
width, height = img.size
for x in range(width):
for y in range(height):
r, g, b = pixels[x, y]
r ^= key
g ^= key
b ^= key
pixels[x, y] = (r, g, b)
# 保存解密后的图片
img.save('decrypted.png')
```
使用方法:
```python
key = 123
filename = 'test.jpg'
# 加密图片
encrypt_image(filename, key)
# 解密图片
decrypt_image('encrypted.png', key)
```
阅读全文