Skip to main content
 首页 » 编程设计

python之创建图像的副本之python

2025年05月04日15thcjp

我正在尝试从图像文件中读取数据并将其写入新文件 - 以制作副本。

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

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) 

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

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

请您参考如下方法:

使用shutil:

import shutil 
shutil.copy("image.png","image2.png") 

或者如你所愿:

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