简体   繁体   English

如何将图像文件导入 python,将其作为数组读取,然后将 output 数组作为相同的图像文件类型

[英]How can i import an image file into python , read it as an array, then output the array as same image file type

I am tasked with writing a program that can take an image file as input, then encrypt the image with some secondary code that i have already written, and finally output the encrypted image file.我的任务是编写一个可以将图像文件作为输入的程序,然后使用我已经编写的一些辅助代码加密图像,最后 output 加密图像文件。

I would like to import an image, make it a 1d array of numbers, perform some encryption on this 1d array (which will make it into a 2d array which i will flatten), and then be able to output the encrypted 1d array as an image file after converting it back to whatever format it was in on input.我想导入一个图像,使其成为一维数字数组,对这个一维数组执行一些加密(这将使它成为一个二维数组,我将把它展平),然后能够将加密的一维数组 output 作为将其转换回输入时的任何格式后的图像文件。

I am wondering how this can be done, and details about what types of image files can be accepted, and what libraries may be required.我想知道如何做到这一点,以及可以接受哪些类型的图像文件以及可能需要哪些库的详细信息。 Thanks谢谢

EDIT: this is some code i have used, img_arr stores the image in an array of integers, max 255. This is what i want, however now i require to convert back into the original format, after i have performed some functions on img_arr.编辑:这是我使用的一些代码,img_arr 将图像存储在一个整数数组中,最大 255。这就是我想要的,但是现在我需要在 img_arr 上执行一些功能后转换回原始格式。

from PIL import Image
    img = Image.open('testimage.jfif')
    print('img first: ',img)
    img = img.tobytes()
    img_arr=[]
    for x in img:
          img_arr.append(x)
    img2=Image.frombytes('RGB',(460,134),img)
    print('img second: ',img2)

my outputs are slightly different我的输出略有不同

img first: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=460x134 at 0x133C2D6F970>
img second: <PIL.Image.Image image mode=RGB size=460x134 at 0x133C2D49EE0>

In programming, Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in an ASCII string format by translating the data into a radix-64 representation.在编程中,Base64 是一组二进制到文本的编码方案,通过将数据转换为基数 64 表示,以 ASCII 字符串格式表示二进制数据(更具体地说,是 8 位字节序列)。

Fortunately, you can encode and decode the image binary file with python based on base64.幸运的是,您可以使用基于 base64 的 python 对图像二进制文件进行编码和解码。 The following link helps you.以下链接可以帮助您。

Encoding an image file with base64 使用 base64 编码图像文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM