如何在Python中将字节数组转换为位图图像?

时间:2018-12-07 16:09:51

标签: python arrays bitmapimage

我正在尝试测试创建一个带有位图图像的异或密钥的简单密码。

import os, io, hashlib
from PIL import Image
from array import array
from itertools import cycle

key = "aaaabbbb"

def generate_keys(key):
    round_keys = hashlib.md5(key).digest()
    return bytearray(round_keys)

def readimage(path):
    with open(path, "rb") as f:
            return bytearray(f.read())

def generate_output_image(input_image, filename_out):
    output_image = Image.open(io.BytesIO(input_image))
    output_image.save(filename_out)

def xor(x,y):
    return [ a ^ b for a,b in zip(x,cycle(y))]

round_keys = generate_keys(key)
input_image = readimage("lena512.bmp")
encrypted_image = xor(input_image, round_keys)
generate_output_image(encrypted_image, "lena_encrypted.bmp")

input_image = readimage("lena_encrypted.bmp");
decrypted_image = xor(input_image, round_keys)
generate_output_image(decrypted_image, "lena_decrypted.bmp")

但是运行脚本时出现以下错误:

Traceback (most recent call last):
    File "test.py", line 26, in <module>
        generate_output_image(encrypted_image, "lena_encrypted.bmp")
    File "test.py", line 17, in generate_output_image
        output_image = Image.open(io.BytesIO(input_image))
TypeError: 'list' does not have the buffer interface

如何将字节数组转换回位图图像? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

更新的脚本将原始图像转换为密码图像,然后转换回原始图像。

import os, io, hashlib, math, binascii
from PIL import Image
from array import array
from itertools import cycle

user_key = "aaaabbbb"
test_image = "lena512.bmp"

def generate_keys(key):
    round_keys = hashlib.md5(key).digest()
    return bytearray(round_keys)

def readimage(path):
    with open(path, "rb") as f:
            return bytearray(f.read())

def generate_output_image(input_image):
    output_image = Image.open(io.BytesIO(input_image))
    output_image.save(test_image)

def xor(x,y):
    return x[:54] + bytearray([a^b for a, b in zip(x[54:], cycle(y))])

round_keys = generate_keys(user_key)
input_image = readimage(test_image)
encrypted_image = xor(input_image, round_keys)
generate_output_image(encrypted_image)

input_image = readimage(test_image);
decrypted_image = xor(input_image, round_keys)
generate_output_image(decrypted_image)

感谢myrmica的帮助

答案 1 :(得分:1)

我进一步研究了如何使用PIL / Pillow中包含的工具更优雅地检索/更新图像数据,并制作了一个简单的工作示例:

from PIL import BmpImagePlugin
import hashlib
from itertools import cycle

keys = hashlib.md5(b"aaaabbbb").digest()

input_image = BmpImagePlugin.BmpImageFile("img/tea.bmp")

# extract pure image data as bytes
image_data = input_image.tobytes()

# encrypt
image_data = bytes(a^b for a, b in zip(image_data, cycle(keys)))

# create new image, update with encrypted data and save
output_image = input_image.copy()
output_image.frombytes(image_data)
output_image.save("img/tea-encrypted.bmp")

这样,您不必担心BMP标头的大小。

(链接:originalencrypted图片)