栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将jpeg大小减小到“所需大小”?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将jpeg大小减小到“所需大小”?

我仍在学习 Python ,因此可能会有更好的方法,但是这里有一个函数可将PIL / Pillow图像另存为JPEG,并允许您指定最大尺寸。

它使用二进制搜索来最大程度地减少所需的工作量,并且将其编码到

BytesIO
内存缓冲区中,以将图像写入磁盘。如果有人有任何改进建议,请告诉我!

#!/usr/local/bin/python3import ioimport mathimport sysimport numpy as npfrom PIL import Imagedef 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)      # Enpre 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 imageim = Image.open('/Users/mark/sample/images/lena.png')# Save at best quality under 100,000 bytesJPEGSaveWithTargetSize(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,枕头,JPEG,质量,质量设置,最大尺寸,最大尺寸,图像,图像处理,二进制搜索。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653360.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号