使用 Feistel 密码和 Python 对图像进行编码
Encode an image with Feistel cipher and Python
我正在尝试使用 Feistel 密码对图像进行编码。我的想法是获取一个图像文件,逐字节读取图像,用我的 Feistel 密码对每个字节进行编码,然后 re-create 使用密码生成的编码字节生成新图像。
不幸的是,我发现大多数常见的图像格式都使用 headers,一旦编码,编码后的图像就会损坏。
查看 PIL 包后,我发现 PIL.Image.frombytes
函数能够在给定 BytesIO
object 的情况下创建图像 object。使用图像 object,我可以使用 save
函数
重新创建图像
我现在的问题是,如何打开图像并读取我需要用我的 Feistel 密码处理的以字节为单位的实际图像负载。
如果我用代码
with open('image.jpg', 'rb') as file:
data = file.read()
我阅读了整个文件,包括我不需要的 headers
最好的解决办法是自己对图像的每个像素进行编码,然后用编码后的新像素重新创建图像
#open image file to process
im = Image.open(file_name, 'r')
#get pixel value
pix_val = list(im.getdata())
#get dimensions
width, height = im.size
tmp = 0
#create image file processed
imge = Image.new("RGB", (width, height))
pix = imge.load() #load the new pixel color
# create image encoded
for x in range(height):
for y in range(width):
#double loop to encode every pixel
pix[y,x] = (encode(pix_val[tmp][0]),encode(pix_val[tmp][1]),encode(pix_val[tmp][2]))
tmp += 1
注意函数encode
应该是你的Feistel密码函数。在这种情况下,它需要一个 8 位整数和 returns 一个 8 位整数(这是每个像素颜色的表示,但可以根据您的需要进行编辑
我正在尝试使用 Feistel 密码对图像进行编码。我的想法是获取一个图像文件,逐字节读取图像,用我的 Feistel 密码对每个字节进行编码,然后 re-create 使用密码生成的编码字节生成新图像。
不幸的是,我发现大多数常见的图像格式都使用 headers,一旦编码,编码后的图像就会损坏。
查看 PIL 包后,我发现 PIL.Image.frombytes
函数能够在给定 BytesIO
object 的情况下创建图像 object。使用图像 object,我可以使用 save
函数
我现在的问题是,如何打开图像并读取我需要用我的 Feistel 密码处理的以字节为单位的实际图像负载。
如果我用代码
with open('image.jpg', 'rb') as file:
data = file.read()
我阅读了整个文件,包括我不需要的 headers
最好的解决办法是自己对图像的每个像素进行编码,然后用编码后的新像素重新创建图像
#open image file to process
im = Image.open(file_name, 'r')
#get pixel value
pix_val = list(im.getdata())
#get dimensions
width, height = im.size
tmp = 0
#create image file processed
imge = Image.new("RGB", (width, height))
pix = imge.load() #load the new pixel color
# create image encoded
for x in range(height):
for y in range(width):
#double loop to encode every pixel
pix[y,x] = (encode(pix_val[tmp][0]),encode(pix_val[tmp][1]),encode(pix_val[tmp][2]))
tmp += 1
注意函数encode
应该是你的Feistel密码函数。在这种情况下,它需要一个 8 位整数和 returns 一个 8 位整数(这是每个像素颜色的表示,但可以根据您的需要进行编辑