如何在Python中将字节数组转换为位图图像? [英] How do I convert byte array to bitmap image in Python?

查看:116
本文介绍了如何在Python中将字节数组转换为位图图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test create a simple cipher that xor key with a bitmap image.

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")

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

But I'm getting the following error when I run the script:

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

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

How do I convert the byte array back into bitmap image? Any help would be appreciated thanks.

推荐答案

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

I looked a bit more into how to retrieve/update the image data more elegantly with the tools included in PIL/Pillow, and made this simple working example:

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标头的大小.

This way, you don't have to worry about the BMP header size.

(链接:原始>和加密图片)

这篇关于如何在Python中将字节数组转换为位图图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆