Image to base64:为什么我在 Python 中调用相同的函数时没有得到相同的 return 值?

Image to base64: Why don't I get the same return value while calling the same function in Python?

我很抱歉提出愚蠢的问题,但我是 Python 的新手,我在 Whosebug 和 google.[=13= 上都没有成功找到我的问题的答案]

例如,我想从 url 获取图像,然后 运行 将其转换为 base64 格式的字符串。我使用 urllib 和 io 模块将 运行sform 一个 link 成对象 然后我两次调用 "tob64" 函数:

import base64
import urllib
import io

fd = urllib.urlopen("http://p2pmailing.co.uk/wp-content/uploads/2013/10/Fashion-And-Modern-Youth.jpg")
img = io.BytesIO(fd.read())

def tob64(image):
    pic = image.read()
    b64 = base64.b64encode(pic)
    return b64

A = tob64(img)
B = tob64(img)

print A==B

I 运行 这段代码我得到了 FALSE 语句。 当我打印出变量 A 时,我得到的实际答案是字符串。 当我打印出变量 B 时,我没有得到任何 return 值。 然而,当我询问 B 的类型时,它会打印出“type 'str'”。 所以实际上它存储在某个地方,但我无法获取它。有什么问题?

在第一个 image.read() 到达 EOF 后,下一个 image.read() 将 return 空字符串,因为没有更多内容可读。您可以使用 image.seek(0) before read 再次读取整个文件。