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

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)
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术与健康

你的鼓励将是我最大的创作动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值