如何用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
相关产品推荐
相关产品推荐

