创建图像的副本-python

Dav*_*sry 1 python binary byte image

我正在尝试从图像文件中读取数据并将其写入新文件-进行复制。

这是我的代码,用于读取原始图像的数据并将每个字节写入新图像:

file = open("image2.png", "w")
with open("image.png", "rb") as f:
    while True:
        byte = f.read(1)
        if not byte:
            break
        file.write(byte)
Run Code Online (Sandbox Code Playgroud)

现在,它确实创建了一个名为“ image2.png”的新文件,但是当我尝试打开它时,出现一个错误,提示图像已损坏或损坏。

如何读取图像数据并将其写入新文件?

jmu*_*sch 6

使用shutil

import shutil
shutil.copy("image.png","image2.png")
Run Code Online (Sandbox Code Playgroud)

或如您所愿:

file = open("image2.png", "wb")
with open("image.png", "rb") as f:
    while True:
        byte = f.read(1)
        if not byte:
            break
        file.write(byte[0])
Run Code Online (Sandbox Code Playgroud)