代码分享: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)
    
相关推荐
伊织code33 分钟前
PyTorch API 5 - 全分片数据并行、流水线并行、概率分布
pytorch·python·ai·api·-·5
风逸hhh1 小时前
python打卡day25@浙大疏锦行
开发语言·python
魔尔助理顾问2 小时前
Flask如何读取配置信息
python·flask·bootstrap
jc_hook3 小时前
Python 接入DeepSeek
python·大模型·deepseek
chicpopoo3 小时前
Python打卡DAY25
开发语言·python
crazyme_64 小时前
深入掌握 Python 切片操作:解锁数据处理的高效密码
开发语言·python
Code_流苏5 小时前
《Python星球日记》 第69天:生成式模型(GPT 系列)
python·gpt·深度学习·机器学习·自然语言处理·transformer·生成式模型
于壮士hoho6 小时前
Python | Dashboard制作
开发语言·python
掘金-我是哪吒6 小时前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
小猪快跑爱摄影6 小时前
【Folium】使用离线地图
python