使用自定义Python cod复制时,图像会损坏

2024-04-25 06:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这是密码

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

我不知道为什么,但这是原始图像

enter image description here

下面是代码的结果图片

enter image description here

我不知道该怎么办,所以我决定来找专家,因为我只有14岁。我还添加了更多类似于TCP通信的内容。所以我可以通过互联网发送文件。你知道吗


Tags: testimagecreating密码closereadmaindef
1条回答
网友
1楼 · 发布于 2024-04-25 06:11:56

您正在用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.

相关问题 更多 >