代码分享:python实现svg图片转换为png和gif

python 复制代码
import cairosvg
import imageio
from PIL import Image
import io
import os


def svg_to_png(svg_path, png_path):
    try:
        cairosvg.svg2png(url=svg_path, write_to=png_path)
        print(f"成功将 {svg_path} 转换为 {png_path}")
    except Exception as e:
        print(f"转换为 PNG 时出错: {e}")


def svg_to_gif(svg_path, gif_path):
    try:
        # 将 SVG 转换为 PNG 图像
        png_bytes = cairosvg.svg2png(url=svg_path)
        image = Image.open(io.BytesIO(png_bytes))

        # 将 PNG 图像保存为 GIF
        image.save(gif_path, save_all=True, append_images=[image], duration=100, loop=0)
        print(f"成功将 {svg_path} 转换为 {gif_path}")
    except Exception as e:
        print(f"转换为 GIF 时出错: {e}")


if __name__ == "__main__":
    current_directory = os.getcwd()
    input_directory = current_directory#os.path.join(current_directory, 'input_svgs')
    output_directory = os.path.join(current_directory, 'output_images')

    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for filename in os.listdir(input_directory):
        if filename.endswith('.svg'):
            svg_file = os.path.join(input_directory, filename)
            base_name = os.path.splitext(filename)[0]
            png_file = os.path.join(output_directory, f'{base_name}.png')
            gif_file = os.path.join(output_directory, f'{base_name}.gif')

            svg_to_png(svg_file, png_file)
            svg_to_gif(svg_file, gif_file)
    
相关推荐
free-elcmacom11 小时前
深度学习<4>高效模型架构与优化器的“效率革命”
人工智能·python·深度学习·机器学习·架构
liliangcsdn12 小时前
python模拟beam search优化LLM输出过程
人工智能·python
王琦031812 小时前
Python 函数详解
开发语言·python
胡伯来了13 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…13 小时前
Python 中的多层继承
开发语言·python
中國移动丶移不动13 小时前
Python MySQL 数据库操作完整示例
数据库·python·mysql
落叶,听雪13 小时前
AI建站推荐
大数据·人工智能·python
ZAz_13 小时前
DAY 45 预训练模型
python
呆萌很14 小时前
python 项目迁移
python
清水白石00814 小时前
《requests vs httpx:Python 网络请求库的全面对比与实战指南》
网络·python·httpx