读取和写入图像文件为 'regular files'
Reading and writing image file as 'regular files'
我必须使用 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 文件无关,因此我假设我对 reading/writing 部分做了一些非常糟糕的事情。
只需写入 image_string,您不需要字节,因为 image_string 在您使用 'rb'
:
打开时已经是一个字节对象
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'>
我必须使用 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 文件无关,因此我假设我对 reading/writing 部分做了一些非常糟糕的事情。
只需写入 image_string,您不需要字节,因为 image_string 在您使用 'rb'
:
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'>