python实现svg图片转换为png和gif

2025-04-24 17:50

本文主要是介绍python实现svg图片转换为png和gif,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

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)

python实现图片格式之间的相互转换

1.概要

图片一般有多种格式,常见的图片格式包括:

  • JPEG(.jpg 或 .jpeg):一种广泛使用的有损压缩格式,适用于摄影图像和网页上的图片。
  • PNG(.png):一种无损压缩格式,支持透明度和更好的图像质量,常用于图标、图形和需要透明背景的图片。该图片是4通道的,外加一个透明通道。如截屏
  • GIF(.gif):一种支持动画和透明度的格式,常用于简单的动画和图标。
  • BMP(.bmp):一种无损格式,存储图像的原始数据,文件大小通常较大,常用于位图处理和打印。
  • TIFF(.tiff 或 .tif):一种高质量的无损格式,支持多页和多种图像深度,常用于印刷和出版。

除了这些常见的格式,还有其他一些图片格式,如 WebP、SVG 等,每种格式都有其特定的用途和优缺点。

图片格式之间的转换涉及到通道数和格式的转换,无尺寸的变换

2.具体代码

from PIL import Image
 
def convert_image(input_path, output_path, output_format):
    # 打开原始图片
    image = Image.open(input_path)
 
    # 获取图片格式
    img_format = image.format
   # 获取通道数
    channels = image.mode
    # 获取尺寸
    width, height = image.size
 
    # 将JPG图片转换为RGB模式(如果图片不是RGB模式)
    if image.mode != "RGB":
        image = image.convert("RGB")
    # 将图片保存为指定格式
    image.save(output_path, format=output_format)
    
    # print(f'Epoch: {best_epoch}, Fold: {best_fold}')
    print(f'输入图片格python式:{img_format}, 输入图片的通道数: {channels}, 输入图片的尺寸: {(width,height)}')
    print("转换完成!")
    print(f'输出图片格式:{output_image_format}, 输出图片的通道数: {image.mode}, 输出图片的尺寸: {(width,height)}')
 
# 设置输入图片路径
input_image_path = "example.jpg"
 
# 设置输出图片路径和格式
output_image_path = "output.png"
output_image_format = "PNG"
 
# 进行图片格式转换
convert_image(input_image_path, output_image_path, output_image_format)

延展:基于Python的图片格式转换工具

介绍

本教程将指导如何使用 Python 编写的图片格式转换工具 IMACon_ter.py,该工具能够将图片从一种China编程格式转换为另一种格式。支持的格式包括:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。

安装依赖

在使用工具之前,请确保已安装 matplotlib。可以使用以下命令进行安装:

pip install matplotlib

工具代码

以下是 ImaCon_ter.py 代码:

# version 1.2
# This software is to convert images to other formats.
# Contact: PersusXie@outlook.com if in doubt

import sys
import matplotlib.pyplot as plt
import os

class ImageConverter:
    def __init__(self, filename, new_format="png"):
        '''
        Initialize the class and call the conversion method
        '''
        self.filename = filename
        self.new_format = new_format
        self.convert()

    def convert(self):
        '''
        Convert the image to the specified format.
        Supported formats: eps, jpeg, jpg, pdf, pgandroidf, png, ps, raw, rgba, svg, svgz, tif, tiff
        '''
        if not os.path.isfile(self.filename):
            print(f"Error: {self.filename} not found in the specified path.")
            return
        
        old_format = self.filename.split(".")[-1]
        if self.new_format == old_format:
            print("The input format is the same as the output format. No conversion needed.")
            return

        supported_formats = ['eps', 'jpeg', 'jpg', 'pdf', 'pgf', 'png', 'ps', 'raw', 'rgba', 'svg', 'svgz', 'tif', 'tiff']
        if self.new_format not in supported_formats:
            print(f"This format is not supported. Supported formats are: {', '.join(supported_formats)}")
            return

        img = plt.imread(self.filename)
        height, width = img.shape[:2]
        dpi = 100

        fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)
        plt.imshow(img)
        plt.axis('off')
        
        new_filename = f"{os.path.splitext(self.filename)[0]}.{self.new_format}"
        plt.savefig(new_filename, format=self.new_format)
        print(f"The new file has been created: {new_filename}")
        plt.close()

def display_help():
    '''
    Display the help message
    http://www.chinasem.cn'''
    print("Usage: python ImaCon_ter.py <filename> <new_format>")
    print("Example: python ImaCon_ter.py image.png svg")
    print("Supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff")
    print("Use -h or --help for this help message.")

def main():
    argvs = sys.argv
    if len(argvs) != 3 or argvs[1] in ["-h", "--help"]:
        display_help()
        return
    
    filename = argvs[1]
    new_format = argvs[2]
    ImageConverter(filename, new_format)

if __name__ == "__main__":
    main()

使用方法

保存脚本:将上述代码保存为 ImaCon_ter.py 文件。

打开终端:在终端中导航到保存脚本的目录。

运行工具: 使用以下格式运行脚本:

www.chinasem.cn
python ImaCon_ter.py <filename> <new_format>

例如,将 image.png 转换为 svg 格式:

python ImaCon_ter.py image.png svg

查看结果:转换完成后,新的图片文件将与原文件位于同一目录下,文件名格式为 <原文件名>.<新格式>。

注意事项

确保输入文件的路径正确,且文件格式支持转换。

支持的输出格式有:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。

若遇到任何问题,可以查看错误消息,确保输入正确,并参考支持的格式列表。

到此这篇关于python实现svg图片转换为png和gif的文章就介绍到这了,更多相关python svg图片转换内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于python实现svg图片转换为png和gif的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154355

相关文章

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

Java的栈与队列实现代码解析

《Java的栈与队列实现代码解析》栈是常见的线性数据结构,栈的特点是以先进后出的形式,后进先出,先进后出,分为栈底和栈顶,栈应用于内存的分配,表达式求值,存储临时的数据和方法的调用等,本文给大家介绍J... 目录栈的概念(Stack)栈的实现代码队列(Queue)模拟实现队列(双链表实现)循环队列(循环数组

使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)

《使用Python从PPT文档中提取图片和图片信息(如坐标、宽度和高度等)》PPT是一种高效的信息展示工具,广泛应用于教育、商务和设计等多个领域,PPT文档中常常包含丰富的图片内容,这些图片不仅提升了... 目录一、引言二、环境与工具三、python 提取PPT背景图片3.1 提取幻灯片背景图片3.2 提取

C++如何通过Qt反射机制实现数据类序列化

《C++如何通过Qt反射机制实现数据类序列化》在C++工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作,所以本文就来聊聊C++如何通过Qt反射机制实现数据类序列化吧... 目录设计预期设计思路代码实现使用方法在 C++ 工程中经常需要使用数据类,并对数据类进行存储、打印、调试等操作。由于数据类

Python实现图片分割的多种方法总结

《Python实现图片分割的多种方法总结》图片分割是图像处理中的一个重要任务,它的目标是将图像划分为多个区域或者对象,本文为大家整理了一些常用的分割方法,大家可以根据需求自行选择... 目录1. 基于传统图像处理的分割方法(1) 使用固定阈值分割图片(2) 自适应阈值分割(3) 使用图像边缘检测分割(4)

Android实现在线预览office文档的示例详解

《Android实现在线预览office文档的示例详解》在移动端展示在线Office文档(如Word、Excel、PPT)是一项常见需求,这篇文章为大家重点介绍了两种方案的实现方法,希望对大家有一定的... 目录一、项目概述二、相关技术知识三、实现思路3.1 方案一:WebView + Office Onl