【问题标题】:file.read() of png file bug? [duplicate]png 文件的 file.read() 错误? [复制]
【发布时间】:2017-02-15 21:02:31
【问题描述】:

我正在尝试以纯文本格式读取 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())

但它不会读取整个文件,例如“读取”功能是假设要做的。 如果我再次尝试为某些 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 中获取此文件吗?

【问题讨论】:

  • 你试过open(f, 'rb')吗?
  • 谢谢,@TigerhawkT3。可以使用这个标志!

标签: python file png


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 2016-08-15
    • 2016-04-04
    • 2020-08-13
    • 2014-11-22
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多