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

Python3不使用第三方库如何获取BMP文件的像素尺寸?

BMP文件像素尺寸获取方案

有多种方案可以实现你需要的获取BMP宽高、总像素数的需求:

方案1:仅使用Python标准库(无需额外安装依赖)

直接读取BMP文件头固定字段获取尺寸,适合不想安装第三方依赖的场景:

import struct

def get_bmp_size(bmp_path: str):
    with open(bmp_path, 'rb') as f:
        # BMP头偏移18字节处存宽度,22字节处存高度,均为小端4字节无符号整数
        f.seek(18)
        width = struct.unpack('<I', f.read(4))[0]
        height = struct.unpack('<I', f.read(4))[0]
    return width, height

# 调用示例
w, h = get_bmp_size('white-small.bmp')
total_pixels = w * h  # 得到你需要的整数结果1024
size_list = [w, h]  # 得到列表形式结果[32, 32]

方案2:使用Pillow库(兼容所有常见图片格式)

如果你的项目已经用到图片处理相关依赖,用Pillow实现更简单,同时支持PNG、JPG等其他格式的尺寸读取:

  1. 未安装Pillow时先执行安装命令:pip install pillow
  2. 调用示例:
from PIL import Image

def get_size_of_bmp(bmp_path: str):
    with Image.open(bmp_path) as img:
        return img.size

# 调用示例
w, h = get_size_of_bmp('white-small.bmp')
total_pixels = w * h # 输出1024

Pillow返回的img.size本身就是(宽度, 高度)格式的元组,可直接按需求转换格式使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:45:02