python - 在不保存的情况下在 Jupyter Notebook 中打开 base64 字符串图像

标签 python python-3.x string base64

我有以下图片:

enter image description here

转换为base64,看起来是这样的:

import base64
filename = 'image.jpg'  

with open(filename, "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
    image_file.close()

with open("encoded_string.txt", "w") as converted_file:
    converted_file.write(str(encoded_string))
    converted_file.close()

在此处下载输出文件 (base64):https://file.io/NXV7v4

现在,我的问题是:

如何检索转换后的图像并将其显示在 jupyter notebook 中,而无需存储?

基于[this][2]问题,我试过:

from PIL import Image
import cv2
import io


# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

stringToRGB(encoded_string)

但是我得到了:

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-43-2564770fa4af> in <module>()
----> 1 stringToRGB(encoded_string)

<ipython-input-42-538f457423e9> in stringToRGB(base64_string)
     18 def stringToRGB(base64_string):
     19     imgdata = base64.b64decode(str(base64_string))
---> 20     image = Image.open(io.BytesIO(imgdata))
     21     return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
   2655         warnings.warn(message)
   2656     raise IOError("cannot identify image file %r"
-> 2657                   % (filename if filename else fp))
   2658 
   2659 #

OSError: cannot identify image file <_io.BytesIO object at 0x00000224D6E7D200>

最佳答案

也许更简单?

from IPython import display
from base64 import b64decode

display.Image(b64decode(base64_data)

关于python - 在不保存的情况下在 Jupyter Notebook 中打开 base64 字符串图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562088/

相关文章:

python - 我想将矩阵转换为列表 python

python-3.x - 局部变量如何在 python 3 的嵌套函数中工作?

python - REST API POST 请求导致 AttributeError : 'bytes' object has no attribute 'items'

c - 用存储在数组中的字符替换字符串中的某些字符会插入垃圾

java - (==) 在 hashCode 方面的功能

python - 从列表中随机选择一对不同的项目

python - 从使用 python pandas 制作的数据透视表中进行过滤和选择

python - Plotly:如何绘制多个 y 轴?

python - 获取数字列表的列表并将它们显示为网格中的字符串

javascript - Jquery .replace 使浏览器崩溃