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

如何用Python检测图片分辨率是否超过1600万像素?

你的代码是可行的!先帮你理清百万像素的含义

首先明确核心概念:1百万像素(megapixel)= 1,000,000 像素,所以1600万像素就是 16 * 1000000 = 16000000 总像素——也就是图片宽度和高度的乘积不能超过这个数值。

你的代码逻辑完全正确:

  • 通过PIL库打开图片并获取尺寸
  • 计算总像素数
  • 和1600万像素阈值对比后输出结果

不过可以给你加一点小优化,让代码更健壮、结果更直观:

from PIL import Image

try:
    im = Image.open("image.jpg")
    width, height = im.size
    total_pixels = width * height
    max_mp = 16 * 10**6  # 用10**6替代硬写的1000000,可读性更强
    
    current_mp = total_pixels / 10**6
    if total_pixels > max_mp:
        print(f"Image has {current_mp:.2f} megapixels, which is greater than 16 megapixels.")
    else:
        print(f"Image has {current_mp:.2f} megapixels, which is less than or equal to 16 megapixels.")
except FileNotFoundError:
    print("Error: The image file was not found.")
except Exception as e:
    print(f"Error opening image: {str(e)}")

这个优化版本保留了你的核心逻辑,还额外做了这些改进:

  • 捕获了文件不存在、图片格式不支持等异常,避免程序直接崩溃
  • 计算并输出具体的百万像素数值,结果更清晰
  • 用10**6替代硬编码的数字,代码可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:10:48