是否有Python PIL的抗锯齿方法?

在进行SVG转换成PNG图片的时候,后续对转换后的图片使用PIL进行操作,结果发现锯齿严重。经过网上搜到,发现只能通过超采样然后缩放的方式来进行抗锯齿操作,效果还不错。

代码参考如下:

import os
import math
import cairosvg

temp_image = os.path.join(fileDir, "splash.png")

# PIL 本身不具备抗锯齿功能,输出的图片锯齿严重,我们进行四倍超采样,然后缩放的方式进行抗锯齿操作
scale = 4.0

# background_color='#FFFFFF'
# 注意如果不设置DPI,默认dpi是96 人眼低于326dpi的可见明显锯齿
cairosvg.svg2png(url=raw, write_to=temp_image, output_width=math.ceil(image_width*scale), dpi=400,
                 output_height=math.ceil(image_height*scale))

from PIL import Image
bg = Image.new("RGBA", (math.ceil(output_width*scale), math.ceil(output_height*scale)))
fg = Image.open(temp_image)
bg.paste(fg, (math.ceil((output_width - image_width)*scale/2),
         math.ceil((output_height - image_height)*scale/2)), fg)

bg.resize((output_width, output_height), Image.ANTIALIAS);
bg.save(out)
os.remove(temp_image)

参考链接


发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注