读取和写入图像文件为“常规文件”

时间:2015-02-13 14:33:58

标签: python image byte

我必须使用Python标准库来读取图像文件,将其数据存储在变量中,然后编写包含后者的新图像文件。我不能简单地复制或移动图像,但这并不重要。我也不能使用像PIL这样的库,我必须坚持Python 3.3。

我正在以这种方式阅读图片内容:

with open(image_path, mode='rb') as image_file:
    image_string = image_file.read()

然后用这种方式写出图像内容:

input_image = # value of the previous function
with open(new_image_path, mode='wb') as dest_image:
    dest_image.write(bytes(input_image, 'UTF-8'))

然而,生成的图像文件似乎已损坏。使用十六进制编辑器快速检查显示我生成的图像文件的数据与常规PNG文件没有任何关系,所以我假设我正在使用读/写部分做一些非常糟糕的事情。

1 个答案:

答案 0 :(得分:0)

只需编写image_string,就不需要字节了,因为当你使用'rb'打开时,image_string已经是一个字节对象了:

dest_image.write(image_string)

with open(image_path,'rb') as image_file:
    image_string = image_file.read()
    with open(new_image_path,'wb') as dest_image:
        dest_image.write(image_string)

print(type(image_string))
<class 'bytes'>