修改图片分辨率,python实现修改图片分辨率
1.修改一张图片分辨率
将input.jpg和output.jpg改成自己的输入输出文件路径
from PIL import Image def resize_image(input_image_path, output_image_path, new_width, new_height): image = Image.open(input_image_path) resized_image = image.resize((new_width, new_height)) resized_image.save(output_image_path) # 使用示例 input_image_path = "input.jpg" output_image_path = "output.jpg" new_width = 800 new_height = 600 resize_image(input_image_path, output_image_path, new_width, new_height)
2.将一个目录(文件夹)上的所有图片修改成相同的分辨率
import os from PIL import Image def resize_images_in_folder(input_folder, output_folder, new_width, new_height): # 遍历输入文件夹中的所有文件 for filename in os.listdir(input_folder): if filename.endswith(".jpg") or filename.endswith(".png"): # 构建输入和输出文件的路径 input_image_path = os.path.join(input_folder, filename) output_image_path = os.path.join(output_folder, filename) # 调用resize_image函数修改图片分辨率 resize_image(input_image_path, output_image_path, new_width, new_height) def resize_image(input_image_path, output_image_path, new_width, new_height): image = Image.open(input_image_path) resized_image = image.resize((new_width, new_height)) resized_image.save(output_image_path) # 使用示例 input_folder = "input_folder" output_folder = "output_folder" new_width = 800 new_height = 600 resize_images_in_folder(input_folder, output_folder, new_width, new_height)