如何用Python-Pillow无损裁剪/模糊PNG,避免色彩失真?
解决Pillow处理PNG的色彩失真与局部模糊需求
一、修复PNG保存时的色彩变暗问题
问题核心是Pillow默认保存PNG时会丢失原图片的ICC色彩配置文件,导致颜色显示偏差;而文件体积减小是PNG无损压缩的正常结果,但色彩配置丢失才是视觉变暗的关键。
修改保存代码,保留原图片的ICC配置文件即可解决:
from PIL import Image with Image.open('test.png') as img: # 获取原图片的ICC色彩配置文件 icc_profile = img.info.get('icc_profile') # 保存时指定配置文件,确保色彩一致 img.save('test copy.png', format='PNG', icc_profile=icc_profile)
如果原图片为调色板模式(P模式),可额外添加palette=Image.Palette.ADAPTIVE参数避免模式转换,多数带alpha通道的PNG用RGBA模式,上述代码已足够。
二、裁剪图片并保留色彩
裁剪操作本身不会影响色彩,只需在裁剪后保存时同样保留ICC配置文件:
from PIL import Image with Image.open('test.png') as img: icc_profile = img.info.get('icc_profile') # 定义裁剪区域:(左, 上, 右, 下) cropped_img = img.crop((100, 100, 500, 500)) # 保存裁剪后的图片,保留色彩配置 cropped_img.save('cropped_test.png', format='PNG', icc_profile=icc_profile)
三、实现局部模糊(匿名化)
通过复制原图片、模糊指定区域、粘贴回原位置的方式实现:
from PIL import Image, ImageFilter with Image.open('test.png') as img: icc_profile = img.info.get('icc_profile') # 定义需要模糊的区域:(左, 上, 右, 下) blur_area = (200, 200, 400, 400) # 复制原图片作为模糊操作的基底 blurred_img = img.copy() # 裁剪目标区域并应用高斯模糊 region = blurred_img.crop(blur_area) region = region.filter(ImageFilter.GaussianBlur(radius=10)) # 将模糊后的区域粘贴回原位置 blurred_img.paste(region, blur_area) # 保存最终图片,保留色彩配置 blurred_img.save('blurred_test.png', format='PNG', icc_profile=icc_profile)
补充说明
GaussianBlur的radius参数控制模糊程度,数值越大模糊效果越强,可按需调整。- 若需同时完成裁剪和局部模糊,先执行裁剪操作,再对裁剪后的图片进行局部模糊处理即可。
内容的提问来源于stack exchange,提问作者Densaugeo
相关产品推荐
相关产品推荐

