You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.3 KiB
43 lines
1.3 KiB
# coding=utf-8
|
|
from PIL import Image
|
|
import os
|
|
|
|
from utils import create_logger
|
|
|
|
logger = create_logger(__name__)
|
|
|
|
|
|
def crop_image_left(image_path, crop_width):
|
|
"""
|
|
从图片左侧切割指定宽度并覆盖原图片
|
|
|
|
参数:
|
|
image_path (str): 图片文件路径
|
|
crop_width (int): 要切割的宽度(像素)
|
|
"""
|
|
try:
|
|
# 打开原始图片
|
|
with Image.open(image_path) as img:
|
|
# 获取图片尺寸
|
|
width, height = img.size
|
|
|
|
# 验证切割宽度是否有效
|
|
if crop_width <= 0 or crop_width >= width:
|
|
raise ValueError(f"切割宽度必须大于0且小于图片宽度({width}px)")
|
|
|
|
# 计算切割区域 (left, upper, right, lower)
|
|
crop_box = (crop_width, 0, width, height)
|
|
|
|
# 执行切割
|
|
cropped_img = img.crop(crop_box)
|
|
|
|
# 临时保存切割后的图片
|
|
temp_path = image_path + ".png"
|
|
cropped_img.save(temp_path, quality=95)
|
|
# 覆盖原文件
|
|
os.replace(temp_path, image_path)
|
|
logger.info(f"成功从左侧切割 {crop_width}px 并覆盖原图")
|
|
except Exception as e:
|
|
print(f"处理图片时出错: {e}")
|
|
if 'temp_path' in locals() and os.path.exists(temp_path):
|
|
os.remove(temp_path)
|