代码分享: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)
    
相关推荐
ahead~1 小时前
【大模型入门】访问GPT_API实战案例
人工智能·python·gpt·大语言模型llm
大模型真好玩2 小时前
准确率飙升!GraphRAG如何利用知识图谱提升RAG答案质量(额外篇)——大规模文本数据下GraphRAG实战
人工智能·python·mcp
19892 小时前
【零基础学AI】第30讲:生成对抗网络(GAN)实战 - 手写数字生成
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·近邻算法
applebomb2 小时前
没合适的组合wheel包,就自行编译flash_attn吧
python·ubuntu·attention·flash
Chasing__Dreams2 小时前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas
彭泽布衣3 小时前
python2.7/lib-dynload/_ssl.so: undefined symbol: sk_pop_free
python·sk_pop_free
喜欢吃豆4 小时前
从零构建MCP服务器:FastMCP实战指南
运维·服务器·人工智能·python·大模型·mcp
一个处女座的测试4 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
nananaij4 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
蛋仔聊测试5 小时前
Playwright 网络流量监控与修改指南
python