file.read() 的 png 文件错误?

file.read() of png file bug?

我正在尝试读取纯文本格式的 PNG 图像,就像在记事本中一样。 (以便稍后转换为 base64)。

测试图片:http://i.imgur.com/yrL3Zz2.png

所以我尝试了这个代码:

f = 'test1.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, file.read())
print
f = 'test2.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, file.read())

但它不会读取整个文件,例如"read"函数是假设做的。 如果我尝试再次为某些 PNG 调用 read,它会再读取一部分,而对于其他的则不会,无论调用的频率如何。

我只有这个输出:

(0, 'test1.png', '\x89PNG\n')
(1, 'test1.png', '')
(2, 'test1.png', '')
(3, 'test1.png', '')
(4, 'test1.png', '')

(0, 'test2.png', '\x89PNG\n')
(1, 'test2.png', '\xd2y\xb4j|\x8f\x0b5MW\x98D\x97\xfc\x13\7\x11\xcaPn\x18\x80,}\xc6g\x90\xc5n\x8cDi\x81\xf9\xbel\xd6Fl\x11\xae\xdf s\xf0')
(2, 'test2.png', '')
(3, 'test2.png', '')
(4, 'test2.png', '')

但我想要这样: http://i.stack.imgur.com/qvuvj.png

这是一个错误?

还有其他(简单的)方法可以在 base64 中获取此文件吗?

PNG 文件不是文本文件;您必须将它们作为二进制文件而不是文本文件来读取,如下所示:

with open(f, 'rb') as file:

如果要生成数据的 base64 编码,请使用 base64 模块:

import base64
f = 'test1.png'
with open(f) as file:
    for i in xrange(0, 5):
        print(i, f, base64.b64encode(file.read()))