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

如何在JavaScript中获取Base64编码图片的尺寸

获取Base64编码图片的宽高方法

以下是几种常见场景下的实现方式:

前端 JavaScript 实现

利用浏览器的Image对象加载Base64图片,在图片加载完成后读取宽高:

// 假设从API获取到的Base64字符串(注意是否带data前缀)
const base64Image = "API返回的Base64编码内容";
const img = new Image();

img.onload = function() {
  console.log("图片宽度:", this.naturalWidth);
  console.log("图片高度:", this.naturalHeight);
};

// 如果API返回的Base64已经包含data:image/xxx;base64,前缀,直接赋值即可
img.src = base64Image.startsWith('data:image') ? base64Image : `data:image/jpeg;base64,${base64Image}`;

注意:需根据实际图片类型调整MIME类型(如png对应image/png),同时可添加img.onerror处理加载失败的情况。

后端 Python 实现

借助Pillow库处理图片,步骤为解码Base64、读取图片流、获取宽高:

  1. 先安装依赖:
pip install pillow
  1. 代码示例:
import base64
from PIL import Image
from io import BytesIO

# 从API获取的Base64字符串
base64_str = "API返回的Base64编码内容"

# 移除可能存在的data前缀
if base64_str.startswith('data:image'):
    base64_str = base64_str.split(',')[1]

# 解码并读取图片
img_bytes = base64.b64decode(base64_str)
with Image.open(BytesIO(img_bytes)) as img:
    width, height = img.size
    print(f"图片宽度:{width},图片高度:{height}")

后端 Java 实现

使用ImageIO和Base64工具类处理:

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import javax.imageio.ImageIO;

public class GetImageSize {
    public static void main(String[] args) throws Exception {
        String base64Str = "API返回的Base64编码内容";
        
        // 移除data前缀(如果存在)
        if (base64Str.startsWith("data:image")) {
            base64Str = base64Str.split(",")[1];
        }
        
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
        
        int width = image.getWidth();
        int height = image.getHeight();
        System.out.println("图片宽度:" + width + ",图片高度:" + height);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:39:27