Python自定义参数实现图像非均等多块裁剪
解决方案:用Pillow或ImageMagick实现非均等图像切片
嘿,这个需求完全能搞定!不用局限于那些只能均等分割的工具,咱可以用灵活的图像处理库或者命令行工具来实现。下面给你两种实用的方案:
方案一:Python + Pillow库(适合编程爱好者)
Pillow是Python里最常用的图像处理库,能精准控制每个切片的裁剪区域。
步骤1:安装Pillow
如果还没装,打开终端跑这个命令:
pip install pillow
步骤2:编写裁剪代码
下面的代码会按照你的要求生成9个切片,每行3个,行高分别为20px、40px、15px,每个切片宽20px:
from PIL import Image # 打开原图像 img = Image.open("your_image.png") # 替换成你的图像路径 img_width, img_height = img.size # 定义每行的高度和统一的切片宽度 row_heights = [20, 40, 15] tile_width = 20 num_cols = 3 # 9个切片=3行×3列 # 检查原图像尺寸是否足够 total_required_height = sum(row_heights) total_required_width = num_cols * tile_width if img_width < total_required_width or img_height < total_required_height: raise ValueError(f"原图像尺寸不够!需要至少宽{total_required_width}px,高{total_required_height}px") # 生成每个切片 tile_count = 1 current_y = 0 for row_height in row_heights: for col in range(num_cols): # 计算当前切片的裁剪区域(左,上,右,下) left = col * tile_width top = current_y right = left + tile_width bottom = top + row_height # 裁剪并保存 tile = img.crop((left, top, right, bottom)) tile.save(f"tile_{tile_count}.png") # 可以改成你想要的格式,比如jpg tile_count += 1 current_y += row_height print("所有切片已生成!")
代码说明
- 先检查原图像尺寸是否满足要求,避免裁剪出错
current_y用来跟踪每行的起始y坐标,逐行往下移动- 每个切片的
left坐标按列数乘以宽度计算,保证每个切片宽度都是20px - 保存的文件名按
tile_1到tile_9的顺序命名,你可以根据需求修改
方案二:ImageMagick命令行(适合不想写代码的用户)
如果你熟悉命令行,ImageMagick的convert工具也能实现,逐个指定每个切片的裁剪区域:
先确保你装了ImageMagick,然后在终端里执行以下命令(替换your_image.png为你的图像路径):
# 第一行3个切片(高20px,宽20px) convert your_image.png -crop 20x20+0+0 tile_1.png convert your_image.png -crop 20x20+20+0 tile_2.png convert your_image.png -crop 20x20+40+0 tile_3.png # 第二行3个切片(高40px,宽20px,起始y=20) convert your_image.png -crop 20x40+0+20 tile_4.png convert your_image.png -crop 20x40+20+20 tile_5.png convert your_image.png -crop 20x40+40+20 tile_6.png # 第三行3个切片(高15px,宽20px,起始y=20+40=60) convert your_image.png -crop 20x15+0+60 tile_7.png convert your_image.png -crop 20x15+20+60 tile_8.png convert your_image.png -crop 20x15+40+60 tile_9.png
命令说明
-crop 宽x高+左偏移+上偏移是核心参数,精准指定每个切片的区域- 第一行的上偏移是0,第二行是20(第一行的高度),第三行是60(20+40)
- 左偏移依次是0、20、40,对应每个20px宽的切片
这两种方案都能完美满足你的需求,选适合自己的就行!
内容的提问来源于stack exchange,提问作者CTOverton
相关产品推荐
相关产品推荐

