影刀RPA 图片批量压缩与格式转换:处理大量素材

发布时间:2026/7/13 1:45:32
影刀RPA 图片批量压缩与格式转换:处理大量素材 title: “影刀RPA 图片批量压缩与格式转换处理大量素材”date: 2026-07-01author: 林焱影刀RPA 图片批量压缩与格式转换处理大量素材电商运营有几百张产品图需要统一压缩到500KB以内、统一转成JPEG、统一加水印、统一改尺寸……这类批量处理任务用影刀Pillow分分钟搞定效果比PS批处理更灵活。什么情况用什么适合批量处理的场景电商主图/详情图统一规格尺寸、格式、大小新闻稿图片批量压缩后发邮件用户上传图片自动压缩节省存储素材图片统一加品牌水印不适合的场景需要专业修图色彩矫正、抠图还是用PS只有几张图手动处理更快怎么做准备工作安装依赖【影刀操作】添加【Python】指令importsubprocess subprocess.run([pip,install,Pillow],capture_outputTrue)print(Pillow安装完成)方法1批量压缩图片到指定大小【影刀操作】添加【Python】指令fromPILimportImageimportosdefcompress_image(input_path,output_path,target_size_kb500,min_quality30): 压缩图片到指定大小KB target_size_kb: 目标大小KB min_quality: 最低质量避免压缩过度 imgImage.open(input_path)# 如果是PNG或其他格式转为RGBJPEG不支持透明通道ifimg.modein(RGBA,P,LA):# 透明背景换成白色backgroundImage.new(RGB,img.size,(255,255,255))ifimg.modeRGBA:background.paste(img,maskimg.split()[3])else:background.paste(img)imgbackgroundelifimg.mode!RGB:imgimg.convert(RGB)# 检查原始大小original_sizeos.path.getsize(input_path)/1024iforiginal_sizetarget_size_kb:# 已经够小只做格式转换img.save(output_path,JPEG,quality85,optimizeTrue)print(f无需压缩{os.path.basename(input_path)}{original_size:.0f}KB)return# 二分法找到合适的quality值quality_low,quality_highmin_quality,95best_outputNonewhilequality_lowquality_high:quality(quality_lowquality_high)//2importiobufferio.BytesIO()img.save(buffer,JPEG,qualityquality,optimizeTrue)size_kbbuffer.tell()/1024ifsize_kbtarget_size_kb:best_outputbuffer.getvalue()quality_lowquality1# 尝试更高质量else:quality_highquality-1# 继续压缩ifbest_output:withopen(output_path,wb)asf:f.write(best_output)final_sizeos.path.getsize(output_path)/1024print(f压缩完成{os.path.basename(input_path)}{original_size:.0f}KB →{final_size:.0f}KB)else:# 质量已经降到最低直接保存img.save(output_path,JPEG,qualitymin_quality,optimizeTrue)print(f压缩至最低质量{os.path.basename(input_path)})# 批量处理input_dirrC:\原始图片output_dirrC:\压缩图片os.makedirs(output_dir,exist_okTrue)image_exts{.jpg,.jpeg,.png,.bmp,.tiff,.webp}processed0forfilenameinos.listdir(input_dir):extos.path.splitext(filename)[1].lower()ifextnotinimage_exts:continueinput_pathos.path.join(input_dir,filename)# 输出统一用jpg后缀output_nameos.path.splitext(filename)[0].jpgoutput_pathos.path.join(output_dir,output_name)compress_image(input_path,output_path,target_size_kb500)processed1print(f\n处理完成共处理{processed}张图片)yda.set_variable(processed_count,processed)方法2批量调整图片尺寸【影刀操作】添加【Python】指令fromPILimportImageimportosdefresize_image(input_path,output_path,target_width800,target_heightNone,modefit,fill_color(255,255,255)): mode: fit - 等比缩放放在目标尺寸内不裁剪可能有留白 fill - 裁剪到精确尺寸 stretch - 强制拉伸到目标尺寸 imgImage.open(input_path)orig_w,orig_himg.sizeiftarget_heightisNone:# 只指定宽度等比缩放ratiotarget_width/orig_w target_heightint(orig_h*ratio)ifmodefit:img.thumbnail((target_width,target_height),Image.LANCZOS)# 居中放置周围填充背景色backgroundImage.new(RGB,(target_width,target_height),fill_color)offset((target_width-img.width)//2,(target_height-img.height)//2)background.paste(img,offset)resultbackgroundelifmodefill:# 先缩放到覆盖目标尺寸再中心裁剪ratiomax(target_width/orig_w,target_height/orig_h)new_wint(orig_w*ratio)new_hint(orig_h*ratio)imgimg.resize((new_w,new_h),Image.LANCZOS)# 中心裁剪left(new_w-target_width)//2top(new_h-target_height)//2resultimg.crop((left,top,lefttarget_width,toptarget_height))else:# stretchresultimg.resize((target_width,target_height),Image.LANCZOS)ifresult.mode!RGB:resultresult.convert(RGB)result.save(output_path,JPEG,quality90,optimizeTrue)# 批量处理电商主图统一800x800input_dirrC:\商品图片\原图output_dirrC:\商品图片\800x800os.makedirs(output_dir,exist_okTrue)forfilenameinos.listdir(input_dir):iffilename.lower().endswith((.jpg,.jpeg,.png)):input_pathos.path.join(input_dir,filename)output_pathos.path.join(output_dir,os.path.splitext(filename)[0].jpg)resize_image(input_path,output_path,800,800,modefill)print(f处理{filename})方法3批量格式转换【影刀操作】fromPILimportImageimportosdefconvert_format(input_dir,output_dir,from_formatpng,to_formatjpg,quality90):批量转换格式os.makedirs(output_dir,exist_okTrue)count0forfilenameinos.listdir(input_dir):ifnotfilename.lower().endswith(.from_format):continueinput_pathos.path.join(input_dir,filename)output_filenameos.path.splitext(filename)[0].to_format output_pathos.path.join(output_dir,output_filename)imgImage.open(input_path)ifto_format.lower()in(jpg,jpeg)andimg.modein(RGBA,P):bgImage.new(RGB,img.size,(255,255,255))ifimg.modeRGBA:bg.paste(img,maskimg.split()[3])else:bg.paste(img)imgbg save_kwargs{quality:quality,optimize:True}ifto_format.lower()in(jpg,jpeg)else{}img.save(output_path,**save_kwargs)count1print(f格式转换完成{count}张{from_format}→{to_format})returncount# PNG批量转JPGconvert_format(rC:\图片\PNG,rC:\图片\JPG,png,jpg)有什么坑坑1PNG透明背景变黑色PNG图有Alpha透明通道直接保存JPEG时透明区域变成黑色而非白色。解决方法保存前先把透明通道合并到白色背景代码里已处理。坑2CMYK格式的图片无法处理印刷厂给的图片是CMYK颜色模式Pillow处理某些CMYK图会出错。解决方法img img.convert(RGB)先转成RGB。坑3图片旋转方向不对手机拍的照片有EXIF旋转信息Pillow默认不处理导致某些图片显示方向不对。解决方法fromPILimportImageOps imgImageOps.exif_transpose(img)# 自动根据EXIF旋转坑4文件名有中文导致报错某些系统路径里的中文文件名处理有问题。解决方法用pathlib.Path代替字符串路径frompathlibimportPathforpinPath(input_dir).glob(*.png):imgImage.open(str(p))总结图片批量处理是Pillow最擅长的场景。压缩用二分法找quality值、调整尺寸区分fit/fill/stretch模式、格式转换注意RGBA→RGB。三个技术点搞清楚几百张图片的处理任务几分钟搞定。