比如有一张很长的图片其大小为宽度779,高度为122552,那我想把图片切分为779乘以1280的格式。
步骤如下:
from PIL import Image
def split_image(image_path, output_path, width, height):
# 加载原始图片
image = Image.open(image_path)
# 确定子图片的宽度和高度
sub_width = width
sub_height = height
# 计算切分的行数和列数
rows = image.height // sub_height
cols = image.width // sub_width
# 遍历每个子图片的位置
for r in range(rows):
for c in range(cols):
# 提取子图片
left = c * sub_width
upper = r * sub_height
right = left + sub_width
lower = upper + sub_height
sub_image = image.crop((left, upper, right, lower))
# 保存子图片
output_filename = f"sub_image_{r}_{c}.jpg"
output_filepath = output_path + "/" + output_filename
sub_image.save(output_filepath)
# 示例用法
image_path = "path/to/your/image.jpg"
output_path = "path/to/save/subimages"
width = 779
height = 1280
split_image(image_path, output_path, width, height)
请确保在运行此代码之前安装了PIL库(使用pip install pillow命令进行安装)。替换示例代码中的image_path、output_path、width和height变量为你自己的路径和参数。执行代码后,将会在指定的output_path目录中保存切分后的子图片。