使用了Python的Pillow库
from PIL import Image
Image.MAX_IMAGE_PIXELS = 2000000000 #设置最大处理像素极限
def convert_image_to_jpg(input_path, output_path, dpi=300):
with Image.open(input_path) as img:
# 设置DPI
img.info['dpi'] = (dpi, dpi)
# 保存为JPG格式,并设置优化参数
img.convert('RGB').save(output_path, 'JPEG', quality=95, dpi=(dpi, dpi), optimize=True)
# 使用函数转换图片
convert_image_to_jpg('/www/busservlib/diyhuoniu_-1_164036446657ea6461800_tplfilter_1-0_merge_x_1_.png', '164036446657ea6461800_tplfilter_1-0_merge.jpg')
开始没有设置像素处理极限,有警告错误
/usr/local/python3/lib/python3.8/site-packages/PIL/Image.py:3011: DecompressionBombWarning: Image size (114276962 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack.
warnings.warn(
^CTraceback (most recent call last):
File "/www/web/py/jpgdpi.py", line 12, in <module>
convert_image_to_jpg('/www/busservlib/diyhuoniu_-1_164036446657ea6461800_tplfilter_1-0_merge_x_1_.png', '164036446657ea6461800_tplfilter_1-0_merge.jpg')
File "/www/web/py/jpgdpi.py", line 9, in convert_image_to_jpg
img.convert('RGB').save(output_path, 'JPEG', quality=95, dpi=(dpi, dpi), optimize=True)
File "/usr/local/python3/lib/python3.8/site-packages/PIL/Image.py", line 934, in convert
self.load()
File "/usr/local/python3/lib/python3.8/site-packages/PIL/ImageFile.py", line 257, in load
n, err_code = decoder.decode(b)
KeyboardInterrupt
设置为20亿像素进行处理,可以成功,设置为none表示不限制,但不建议这种无设置极限的逻辑。
标签:convert,python,Image,py,jpg,300,path,dpi From: https://www.cnblogs.com/anniu1122/p/18222096