pillow压缩gif图片
pillow10.1.0 + python3.10
python
from PIL import Image
def compress_gif(input_path, output_path):
# 打开原始GIF文件
image = Image.open(input_path)
print(image.n_frames)
# 将每一帧保存为单独的图片
frames = []
for frame in range(0, image.n_frames):
image.seek(frame)
# 创建新的Image对象并设置相同大小、模式等属性
new_frame = Image.new("RGBA", image.size)
new_frame.paste(image, (0, 0))
# 添加到帧列表中
frames.append(new_frame)
# 重新构造GIF动画
compressed_gif = Image.new('RGBA', image.size)
compressed_gif.save(output_path, save_all=True, append_images=frames, loop=0)
# 调用函数进行压缩
compress_gif("y.gif", "x.gif")
效果:
bash
# before
y.gif 12426kb
# after
x.gif 6166kb
svg to png
需要下载这个模块,官网:https://cairosvg.org/
bash
pip install cairosvg
demo:
python
from cairosvg import svg2png
svg_flie_str = open('./xx.svg', 'r').read()
svg2png(bytestring=svg_flie_str,write_to='output.png')
但大概率执行失败:
bash
OSError: no library called "cairo-2" was found
no library called "cairo" was found
no library called "libcairo-2" was found
cannot load library 'libcairo.so.2': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libcairo.so.2'
cannot load library 'libcairo.2.dylib': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libcairo.2.dylib'
cannot load library 'libcairo-2.dll': error 0x7e. Additionally, ctypes.util.find_library() did not manage to locate a library called 'libcairo-2.dll'
解决办法就是从这个地址:https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases下载:
安装到本地之后,直接双击安装,一个配置都不动的一路下一步。
完事之后,重启你的vscode或者pycharm软件,重新尝试,再报错就重启电脑。 ��