将透明图片字体画布居中
from PIL import Image, ImageChops
import os
def center_content(image_path, output_path):
# 打开图片并转为RGBA模式以保持透明度
img=Image.open(image_path).convert("RGBA")
# 使用一个空白画布来找出图像中的内容边界
blank=Image.new("RGBA", img.size, (255, 255, 255, 0))
diff=ImageChops.difference(img, blank)
bbox=diff.getbbox()
ifnotbbox:
print(f"No content detected for {image_path}. Skipping...")
return
# 计算需要移动的偏移量
x_offset= (img.width- (bbox[2] -bbox[0])) //2-bbox[0]
y_offset= (img.height- (bbox[3] -bbox[1])) //2-bbox[1]
# 移动内容
img=ImageChops.offset(img, x_offset, y_offset)
# 根据输出文件的扩展名保存图像
ifoutput_path.lower().endswith(".jpg") oroutput_path.lower().endswith(".jpeg"):
img.convert("RGB").save(output_path, "JPEG")
elifoutput_path.lower().endswith(".png"):
img.save(output_path, "PNG")
else:
img.save(output_path)
# 批量处理文件夹中的所有图片
input_folder = '修改后'
for img_file in os.listdir(input_folder):
ifimg_file.lower().endswith(('.png', '.jpg', '.jpeg')):
image_path=os.path.join(input_folder, img_file)
output_path=os.path.join(input_folder, f"centered_{img_file}")
center_content(image_path, output_path)
附加代码,将字体做红框标记出来。
from PIL import Image, ImageDraw
import os
def center_content(image_path, output_path):
# 打开图片并转为RGBA模式保持透明度
img=Image.open(image_path).convert("RGBA")
width, height=img.size
# 获取非透明部分的边界(使用alpha通道确定边界)
bbox=img.split()[3].getbbox()
ifnotbbox:
print(f"No content detected for {image_path}. Skipping...")
return
# 计算毛笔字应该放置的位置
x_offset= (width- (bbox[2] -bbox[0])) //2-bbox[0]
y_offset= (height- (bbox[3] -bbox[1])) //2-bbox[1]
# 移动内容
img=img.transform(img.size, Image.AFFINE, (1, 0, x_offset, 0, 1, y_offset))
# For diagnostic: Draw the bounding box of the detected content
draw=ImageDraw.Draw(img)
draw.rectangle(bbox, outline="red")
# 根据输出文件的扩展名保存图像
ifoutput_path.lower().endswith(".jpg") oroutput_path.lower().endswith(".jpeg"):
img.convert("RGB").save(output_path, "JPEG")
elifoutput_path.lower().endswith(".png"):
img.save(output_path, "PNG")
else:
img.save(output_path)
# 批量处理文件夹中的所有图片
input_folder = '修改后'
for img_file in os.listdir(input_folder):
ifimg_file.lower().endswith(('.png', '.jpg', '.jpeg')):
image_path=os.path.join(input_folder, img_file)
output_path=os.path.join(input_folder, f"centered_{img_file}")
center_content(image_path, output_path)