萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python 獲取遠程圖片尺寸與大小:無需落盤的內存流方案

核心代碼:urllib + BytesIO + PIL

import io
import urllib.request
from PIL import Image

def get_remote_image_info(url, timeout=10):
    try:
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            data = resp.read()
        
        # 內存流包裝
        stream = io.BytesIO(data)
        with Image.open(stream) as im:
            # 強制加載以獲取尺寸(某些格式需 load())
            im.load()
            return {
                'format': im.format,      # JPEG, PNG, GIF...
                'size': im.size,          # (width, height)
                'mode': im.mode,          # RGB, RGBA, P...
                'content_length': len(data),
                'content_type': resp.headers.get('Content-Type')
            }
    except Exception as e:
        return {'error': str(e)}

# 使用
info = get_remote_image_info('https://jb51.net/images/logo.gif')
print(info)
# {'format': 'GIF', 'size': (200, 60), 'mode': 'P', 'content_length': 4523, ...}

關鍵點

  • Image.open(BytesIO) 不讀取像素數據,極快
  • im.load() 觸發解碼,獲取真實尺寸(對於某些格式如 PNG 可能需要)
  • 不寫入磁盤,適合爬蟲、驗證、預覽生成
  • 大文件注意內存佔用,可改用 urllib.request.urlopen 流式讀取 + ImageFile.Parser 增量解碼

增量解析大圖(不載入完整文件)

from PIL import ImageFile
import urllib.request

def get_size_streaming(url):
    parser = ImageFile.Parser()
    with urllib.request.urlopen(url) as resp:
        while True:
            chunk = resp.read(8192)
            if not chunk: break
            parser.feed(chunk)
            if parser.image:
                return parser.image.size  # 解析到尺寸即停止
    return None
copyright © 萬盛學電腦網 all rights reserved