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

标签 python image return base64

我很抱歉问了这个愚蠢的问题,但我是 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/

相关文章:

php - 上传的图像未正确存储在数据库中(php mysql)

java - 简单的return语句错误

cocoa - 返回数组的正确方法

python - 如何使用python在二维网格中找到最近的相邻点坐标

python - Scipy/python 中分段函数的优化

python - 在 tkinter 中中断嵌入式 pygame 会跳过 KEYUP 事件并认为该键仍被按下

java - 如果 JPEG 为 10MB,java.awt.Image 将消耗多少内存?

c# - 在 C# 中从谷歌搜索中提取图像

python - 使用 C-API 在 Numpy 数组中反转轴

java - 如何根据 String 类型方法(java)中的 if 语句返回多个值?