python - 加载base64图像时出错: PIL. UnidentifiedImageError : cannot identify image file <_io. BytesIO

标签 python base64 python-imaging-library bytesio

我有一个字符串 base64 图像需要转换,这样我就可以将其读取为图像以使用 pytesseract 进行分析:

import base64
import io
from PIL import Image
import pytesseract
import sys


base64_string = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFh....."

img_data = base64.b64decode(base64_string)

img = Image.open(io.BytesIO(img_data)) # <== ERROR LINE

text = pytesseract.image_to_string(img, config='--psm 6')

print(text)

给出错误:

Traceback (most recent call last):
  File "D:\aa\xampp\htdocs\xbanca\aa.py", line 14, in <module>
    img = Image.open(io.BytesIO(img_data))
  File "D:\python3.10.10\lib\site-packages\PIL\Image.py", line 3283, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000001A076F673D0>

我尝试使用 numpy 和 request 库,但都有相同的结果..并且 base64 示例图像在任何其他转换器中都可以正常工作。

最佳答案

这是一个非常常见的误解。 字符串

base64_string = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFh....."

不是 Base64 字符串,而是 DataURL

URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents

包含一个 Base64 字符串。 Base64 字符串直接在“base64,”之后开始。因此,您需要剪掉 'data:image/jpeg;base64,' 部分。

例如:

b64 = base64_string.split(",")[1]

之后您可以解码数据:

img_data = base64.b64decode(b64)

我修改了问题中的代码并使用了以下小JPEG图像的base64,该图像是我在 https://www.base64encode.org/ 上进行base64编码的: enter image description here

并得到了预期的文本输出:

1 Answer

关于python - 加载base64图像时出错: PIL. UnidentifiedImageError : cannot identify image file <_io. BytesIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75498214/

相关文章:

python - PyMySQL 其中类似通配符包围变量

python - Kivy:使用 ListAdapter 或 DictAdapter 更新 ListView 数据不会更改按钮文本

python - python : A better way to run a function when an error occurs in the program?

java - 无法将 base64 编码的字符串映射到 JAXRS 中的 Restful 实现

java - 使用 SOAP 处理二进制数据

python - 如何在存储到磁盘之前使用 Pillow-python 获取以 KB 为单位的图像大小?

Python列出数组中每个元素的命名索引?

jquery - 在 Javascript/jQuery 中解码 base64 文件以供下载

Python读取多层PSD?

Python库安装