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

如何将PNG文件转换为Base64并存入以image为键的JSON数组?

实现步骤

1. 将PNG文件转换为带前缀的Base64字符串

先把PNG文件的二进制内容编码为Base64,再拼接data:image/png;base64,前缀,得到目标格式的完整字符串。

Python 示例

import base64

# 读取PNG二进制内容并编码为Base64
with open("your_image.png", "rb") as img_file:
    base64_content = base64.b64encode(img_file.read()).decode("utf-8")
# 添加格式前缀
full_base64_str = f"data:image/png;base64,{base64_content}"

JavaScript(Node.js)示例

const fs = require("fs");

// 读取文件并直接编码为Base64
const base64Content = fs.readFileSync("your_image.png", "base64");
// 拼接前缀
const fullBase64Str = `data:image/png;base64,${base64Content}`;

2. 拆分字符串并存入JSON数组

拆分时要把前缀保留在第一个数组元素里,剩余内容按固定长度(示例中为76字符,符合Base64的换行规范)分割,最后将所有片段放到image键对应的数组中。

Python 示例

# 定义拆分的单段长度
chunk_size = 76

# 分离前缀和纯Base64内容
prefix_end_pos = full_base64_str.find(",") + 1
prefix = full_base64_str[:prefix_end_pos]
content = full_base64_str[prefix_end_pos:]

# 生成拆分后的数组
image_array = []
# 第一个元素:前缀 + 第一段内容(补足到指定长度)
first_chunk_len = chunk_size - len(prefix)
image_array.append(prefix + content[:first_chunk_len])

# 拆分剩余内容
for i in range(first_chunk_len, len(content), chunk_size):
    image_array.append(content[i:i+chunk_size])

# 组装成目标JSON结构
result = {"image": image_array}

# 可选:保存为JSON文件
import json
with open("output.json", "w") as f:
    json.dump(result, f, indent=2)

JavaScript(Node.js)示例

// 定义单段长度
const chunkSize = 76;

// 拆分前缀和内容部分
const prefixEndIndex = fullBase64Str.indexOf(",") + 1;
const prefix = fullBase64Str.slice(0, prefixEndIndex);
const content = fullBase64Str.slice(prefixEndIndex);

// 构建数组
const imageArray = [];
// 处理第一个元素:前缀+第一段内容
const firstChunkLen = chunkSize - prefix.length;
imageArray.push(prefix + content.slice(0, firstChunkLen));

// 循环拆分剩余内容
for (let i = firstChunkLen; i < content.length; i += chunkSize) {
    imageArray.push(content.slice(i, i + chunkSize));
}

// 组装成JSON对象
const result = { image: imageArray };

// 可选:保存为JSON文件
fs.writeFileSync("output.json", JSON.stringify(result, null, 2));

说明:拆分长度可按需调整,示例用76字符是遵循MIME格式中Base64的换行标准,和你给出的示例格式匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:27:51