代码检查图片大小

要检查图片的大小,我们可以使用Python的PIL库,以下是一个简单的示例:
from PIL import Image def check_image_size(image_path): """ 检查给定路径的图片大小(宽度和高度)。 参数: image_path (str): 图片文件的路径。 返回: tuple: 包含图片宽度和高度的元组。 """ with Image.open(image_path) as img: width, height = img.size return width, height 示例用法 image_path = "example.jpg" width, height = check_image_size(image_path) print(f"图片宽度: {width}px, 高度: {height}px")
在这个示例中,我们首先导入了Image
模块,然后定义了一个名为check_image_size
的函数,该函数接受一个图片路径作为参数,使用Image.open()
方法打开图片,然后通过访问img.size
属性来获取图片的宽度和高度,函数返回一个包含宽度和高度的元组。
相关问题与解答
1、问题:如何修改上述代码以检查多个图片的大小?
答案: 如果要检查多个图片的大小,可以将check_image_size
函数放入一个循环中,遍历所有图片路径。
“`python
image_paths = ["image1.jpg", "image2.jpg", "image3.jpg"]
for image_path in image_paths:

width, height = check_image_size(image_path)
print(f"{image_path} 宽度: {width}px, 高度: {height}px")
“`
2、问题:如何将图片大小信息保存到文件中?
答案: 要将图片大小信息保存到文件中,可以使用Python的文件操作功能,以下是一个示例:
“`python
from PIL import Image
def save_image_sizes_to_file(image_paths, output_file):

"""
将多个图片的大小信息保存到指定的文件中。
参数:
image_paths (list): 图片文件路径的列表。
output_file (str): 输出文件的路径。
"""
with open(output_file, ‘w’) as f:
for image_path in image_paths:
with Image.open(image_path) as img:
width, height = img.size
f.write(f"{image_path} 宽度: {width}px, 高度: {height}pxn")
# 示例用法
image_paths = ["image1.jpg", "image2.jpg", "image3.jpg"]
output_file = "image_sizes.txt"
save_image_sizes_to_file(image_paths, output_file)
“`
这个函数save_image_sizes_to_file
接受一个图片路径列表和一个输出文件路径作为参数,它遍历每个图片路径,获取其大小,并将结果写入指定的输出文件中。
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复