gpt4 book ai didi

python - 图像转base64 : Why don't I get the same return value while calling the same function in Python?

转载 作者:行者123 更新时间:2023-12-01 04:05:56 25 4
gpt4 key购买 nike

我很抱歉问了这个愚蠢的问题,但我是 Python 的新手,我在 stackoverflow 和 google 上都没有成功找到我的问题的答案。

例如,我想从 url 获取图像并将其传输为 base64 格式的字符串。我使用 urllib 和 io 模块将链接转换为对象然后我两次调用我的“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

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

最佳答案

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

关于python - 图像转base64 : Why don't I get the same return value while calling the same function in Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com