编写图像文件大小调整程序并使用Python获得Int不可迭代的问题

问题描述

我一般都不是编程新手,而是尝试使用Python制作一个可以调整图像大小以减小文件大小(磁盘大小)的程序。我的输出测试似乎还可以,但是当我去编写一个循环以使文件越来越小直到匹配所需大小(以字节为单位)时,我遇到了一个问题。

Output:
Enter image file name to resize: Zophie.jpg
Image file is:  Zophie.jpg
<class 'numpy.ndarray'>
(533,400,3)
<class 'tuple'>
Current image size in bytes:  31743
Image width:  533
Image height:  400
Enter desired image size in bytes: 20000
Traceback (most recent call last):
  File "C:\python\image_size.py",line 29,in <module>
    image_copy = image_copy.thumbnail(int(width - 10))
  File "C:\Users\pro\AppData\Local\Programs\Python\python39\lib\site-packages\PIL\Image.py",line 2299,in thumbnail
    x,y = map(math.floor,size)
TypeError: 'int' object is not iterable
from PIL import Image
import os
import cv2

# Get image path (current working directory only at this point)
image_path = input("Enter image file name to resize: ")

# Make an Image object with image from image_path
image_file = Image.open(image_path)

# Make a copy of image_file to work with while resizing
image_copy = image_file.copy()

# Verify the correct image is chosen
print("Image file is: ",image_path)

# Get the image size in bytes
image_size = os.stat(image_path).st_size

# Use cv2 to generate an unpackable tuple to assign width and height to
img = cv2.imread(image_path)

# Check types
print(type(img))
print(img.shape)
print(type(img.shape))

# Tuple unpacking
height,width,channel = img.shape

# display stats for current image
print("Current image size in bytes: ",image_size)
print("Image width: ",width)
print("Image height: ",height)

# Get the desired size for new image
desired_size = int(input("Enter desired image size in bytes: "))

# Pray,and pray hard for a result (lost at this point)
while image_size > desired_size:
    image_copy = image_copy.thumbnail(width - 10)
    image_copy.save(image_file)
    image_size = os.stat(image_file).st_size

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)