如何解决编写图像文件大小调整程序并使用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 举报,一经查实,本站将立刻删除。