You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在内存中实现Base64字符串与NumPy数组的编解码?

在内存中实现Base64与NumPy数组的互转方案

当然有!完全可以全程在内存中完成Base64字符串和NumPy数组的编解码,不需要任何磁盘IO操作。下面是基于Python常用库的简洁实现方法:

一、Base64字符串转NumPy数组

我们可以借助base64、PIL/Pillow和BytesIO来完成内存中的转换,步骤很清晰:

  • 解码Base64字符串得到图像字节流
  • 用BytesIO将字节流包装成类文件对象,供PIL读取
  • 将PIL图像直接转换为NumPy数组

示例代码:

import base64
import numpy as np
from PIL import Image
from io import BytesIO

def base64_to_numpy(base64_str):
    # 处理带data URI前缀的Base64字符串(比如前端传来的格式)
    if 'base64,' in base64_str:
        base64_str = base64_str.split('base64,')[1]
    
    # 解码Base64为字节数据
    img_bytes = base64.b64decode(base64_str)
    # 内存中打开图像
    img = Image.open(BytesIO(img_bytes))
    # 转换为NumPy数组
    return np.array(img)

二、NumPy数组转Base64字符串

反向转换的思路类似,把NumPy数组先转成PIL图像,再在内存中保存为字节流,最后编码为Base64:

  • 将NumPy数组转换为PIL图像(注意数组维度要符合图像格式,比如彩色图是(H,W,3),灰度图是(H,W))
  • 用BytesIO在内存中存储图像字节
  • 将字节数据编码为Base64字符串,可选添加data URI前缀

示例代码:

import base64
import numpy as np
from PIL import Image
from io import BytesIO

def numpy_to_base64(arr, img_format='PNG'):
    # 确保数组数据类型符合PIL要求(比如uint8)
    if arr.dtype != np.uint8:
        arr = arr.astype(np.uint8)
    
    # NumPy数组转PIL图像
    img = Image.fromarray(arr)
    # 内存中保存图像字节
    buffer = BytesIO()
    img.save(buffer, format=img_format)
    # 编码为Base64字符串并解码为UTF-8文本
    base64_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
    
    # 可选:返回带data URI前缀的格式,方便直接用于网页或其他场景
    return f'data:image/{img_format.lower()};base64,{base64_str}'

小提示

  • 先安装依赖库:用pip install pillow numpy就能搞定
  • 如果处理的是浮点型NumPy数组,必须先转成uint8类型(PIL只认整数像素值)
  • 图像格式支持PNG、JPG、BMP等PIL兼容的类型,按需选就行

内容的提问来源于stack exchange,提问作者huangbiubiu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:18:00