使用自定义 Python 代码复制时图像损坏

Image gets corrupted when copied using custom Python code

这是代码

def main():
    f = open("image.jpg", "rb")
    filedata = f.read()
    f.close()
    print "Creating Test Image"
    f = open("ftp_test.jpg", "w+")
    f.write(filedata)
    f.close()
    print "Done!"

if __name__ == '__main__':
    main()

我不确定,但这是原始图像

这是代码

生成的图片

我不确定该怎么做,所以我决定去找专家,因为我只有 14 岁。我还在添加更多内容,例如 TCP 通信。这样我就可以通过互联网发送文件了。

您正在使用 rb 读取二进制文件,因此也使用 wb.

以二进制形式写回文件
f = open("ftp_test.jpg", "wb+")

来自官方docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.