篇幅原因本文没有介绍一些python使用细节,代码中方法内部的涉及的小算法也没有详细的解析。本文最主要的目的是分析图片批处理过程的整体思路,python是解决这个问题的一个工具,使用其它编程语言同样可以完美完成,不过可能不会有python来得方便。
对于图片的批处理,也可以发挥更多的想象力,完成更高级的任务,比如封装成应用程序的形式、不通过文件名获取文件的生成日期信息、识别图片中的关键点并以此为中心进行缩放等,这些任务都非常有趣,不过既然是追求效率,那就贯彻到底,又快又好的完成我们的需求就足够了。
完整代码: from PIL import Image, ImageDraw, ImageFont import os import re font = ImageFont.truetype(r\'C:\Windows\Fonts\msyh.ttc\', size=80) def get_pathtime_dict(path_root): raw_paths = os.listdir(path_root) path_time_dict = {} pattern = re.compile(r\'_(\d{8})\d*\') for path in raw_paths: if path[-4:] != \'.jpg\': continue timeinfo = pattern.findall(path) if timeinfo: label = timeinfo[0][:4]+\'/\' + \ timeinfo[0][4:6] + \'/\' + timeinfo[0][6:] path_time_dict[path] = label return path_time_dict def text2img(img, text, font=font): rgba_img = img.convert(\'RGBA\') # Create an overlay for the texts text_overlay = Image.new(\'RGBA\', rgba_img.size, (0, 255, 0, 0)) image_draw = ImageDraw.Draw(text_overlay) # Set the properties of the texts text_wdth, text_hgt = image_draw.textsize(text, font=font) text_sz = (rgba_img.size[0] - text_wdth - 50, rgba_img.size[1] - text_hgt - 50) image_draw.text(text_sz, text, font=font, fill=(255, 0, 0, 180)) img_with_text = Image.alpha_composite(rgba_img, text_overlay) return img_with_text def img_resize(img, trgtsize): \'\'\' Zoom an image based on the center of the image to fit the target size, with the redundant section trimmed :param trgtsize: tatget size for the img normalization \'\'\' trgtsize = tuple(trgtsize) img_wdth, img_hgt = img.size if img_wdth > img_hgt: trgtsize = (max(trgtsize), min(trgtsize)) else: trgtsize = (min(trgtsize), max(trgtsize)) target_wdth, target_ght = trgtsize # Fit the source image to the target size with the redundant part trimmed center_px = (img_wdth / 2, img_hgt / 2) zoom_fct = min(img_wdth / target_wdth, img_hgt / target_ght) box_wdth, box_hgt = target_wdth*zoom_fct, target_ght*zoom_fct box_start_pt = (int(center_px[0]-box_wdth/2), int(center_px[1]-box_hgt/2)) box_end_pt = (int(center_px[0]+box_wdth/2), int(center_px[1]+box_hgt/2)) resized_img = img.resize(trgtsize, box=( box_start_pt[0], box_start_pt[1], box_end_pt[0], box_end_pt[1])) return resized_img def main(): path_root = r\'C:\Users\Windy\Desktop\Python照片批处理\images_we\' path_time_dict = get_pathtime_dict(path_root) nrml_sz = (1051, 1500) for path, text in path_time_dict.items(): img_pre = Image.open( r\'C:\Users\Windy\Desktop\Python照片批处理\images_we\{}\'.format(path)) img_nrml = img_resize(img_pre, nrml_sz) img_pos = text2img(img_nrml, text) img_pos.save( # remove the \'.jpg\' suffix from an image file\'s path r\'C:\Users\Windy\Desktop\Python照片批处理\images_we\new\_{}.png\'.format(path[:-4])) print(\'image {} done!\'.format(path)) img_pre.close() main() print(\'OK~\')