如何将jpeg大小减小为“所需大小"? [英] How to reduce a jpeg size to a 'desired size'?

查看:101
本文介绍了如何将jpeg大小减小为“所需大小"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3.x中,我使用PIL调整图像大小,我知道我们可以通过减法或按像素划分来减小高度或宽度.但是,是否可以将图像调整为所需大小,例如200kb,并保持其比例不变?假设图像较大,但尺寸未知.

In Python 3.x, I am using PIL to resize images, I know that we can reduce the height or width by subtraction or division by pixels. But, is it possible to resize an image to a desired size, say 200kb and remain its proportions? Assuming the image(s) is larger but the size is unknown.

推荐答案

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

I am still learning Python, so there may be better ways, but here is a function that saves a PIL/Pillow image as a JPEG and allows you to specify a maximum size.

它使用二进制搜索来减少所需的工作量,并编码为BytesIO内存缓冲区,以将图像写入磁盘.如果有人有任何改进建议,请告诉我!

It uses a binary search to minimise the amount of work needed and it encodes into BytesIO memory buffer to save writing images to disk. If anyone has any suggestions for improvements, please let me know!

#!/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字节,我将得到:

If I run that as is, with target size of 100,000 bytes, I get:

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

如果将目标大小更改为50,000字节,则会得到:

If I change the target size to 50,000 bytes, I get:

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

关键字:Python,PIL,Pillow,JPEG,质量,质量设置,最大尺寸,最大尺寸,图像,图像处理,二进制搜索.

Keywords: Python, PIL, Pillow, JPEG, quality, quality setting, max size, maximum size, image, image processing, binary search.

这篇关于如何将jpeg大小减小为“所需大小"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆