如何将 jpeg 尺寸缩小到“所需尺寸”?
- 2025-02-18 09:25:00
- admin 原创
- 38
问题描述:
在 Python 3.x 中,我使用 PIL 调整图像大小,我知道我们可以通过减法或除法来减小高度或宽度。但是,是否可以将图像调整为所需大小(例如 200kb)并保持其比例?假设图像较大但大小未知。
解决方案 1:
我仍在学习Python,因此可能有更好的方法,但这里有一个函数可以将 PIL/Pillow 图像保存为 JPEG,并允许您指定最大尺寸。
它使用二进制搜索来最小化所需的工作量,并将图像编码到BytesIO
内存缓冲区中以节省将图像写入磁盘的时间。如果有人有任何改进建议,请告诉我!
#!/usr/local/bin/python3
import io
import math
import sys
import numpy as np
from PIL import Image
def JPEGSaveWithTargetSize(im, filename, target):
"""Save the image as JPEG with the given name at best quality that makes less than "target" bytes"""
# Min and Max quality
Qmin, Qmax = 25, 96
# Highest acceptable quality found
Qacc = -1
while Qmin <= Qmax:
m = math.floor((Qmin + Qmax) / 2)
# Encode into memory and get size
buffer = io.BytesIO()
im.save(buffer, format="JPEG", quality=m)
s = buffer.getbuffer().nbytes
if s <= target:
Qacc = m
Qmin = m + 1
elif s > target:
Qmax = m - 1
# Write to disk at the defined quality
if Qacc > -1:
im.save(filename, format="JPEG", quality=Qacc)
else:
print("ERROR: No acceptble quality factor found", file=sys.stderr)
################################################################################
# main
################################################################################
# Load sample image
im = Image.open('/Users/mark/sample/images/lena.png')
# Save at best quality under 100,000 bytes
JPEGSaveWithTargetSize(im, "result.jpg", 100000)
如果我按原样运行该程序,目标大小为 100,000 字节,我得到:
-rw-r--r--@ 1 mark staff 96835 11 Sep 18:21 result.jpg
如果我将目标大小更改为 50,000 字节,我会得到:
-rw-r--r--@ 1 mark staff 49532 11 Sep 18:26 result.jpg
关键词: Python、PIL、Pillow、JPEG、质量、质量设置、最大尺寸、最大尺寸、图像、图像处理、二分搜索。
相关推荐
热门文章
项目管理软件有哪些?
- 2025年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)
热门标签
云禅道AD