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

2024-04-19 12:57:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3.x中,我使用PIL来调整图像大小,我知道我们可以通过像素的减法或除法来减少高度或宽度。但是,是否可以将图像大小调整为所需大小(例如200kb)并保持其比例?假设图像较大,但大小未知


Tags: 图像宽度pil高度像素python3比例
1条回答
网友
1楼 · 发布于 2024-04-19 12:57:12

我仍在学习Python,所以可能有更好的方法,但这里有一个函数,可以将PIL/枕头图像保存为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)

如果按原样运行,目标大小为100000字节,则会得到:

-rw-r r @   1 mark  staff     96835 11 Sep 18:21 result.jpg

如果我将目标大小更改为50000字节,我会得到:

-rw-r r @   1 mark  staff     49532 11 Sep 18:26 result.jpg

关键词:Python、PIL、枕头、JPEG、质量、质量设置、最大大小、最大大小、图像、图像处理、二进制搜索

相关问题 更多 >