python實(shí)現(xiàn)svg圖片轉(zhuǎn)換為png和gif
python實(shí)現(xiàn)svg圖片轉(zhuǎn)換為png和gif
實(shí)現(xiàn)代碼
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} 轉(zhuǎn)換為 {png_path}")
except Exception as e:
print(f"轉(zhuǎn)換為 PNG 時(shí)出錯(cuò): {e}")
def svg_to_gif(svg_path, gif_path):
try:
# 將 SVG 轉(zhuǎn)換為 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} 轉(zhuǎn)換為 {gif_path}")
except Exception as e:
print(f"轉(zhuǎn)換為 GIF 時(shí)出錯(cuò): {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實(shí)現(xiàn)圖片格式之間的相互轉(zhuǎn)換
1.概要
圖片一般有多種格式,常見(jiàn)的圖片格式包括:
- JPEG(.jpg 或 .jpeg):一種廣泛使用的有損壓縮格式,適用于攝影圖像和網(wǎng)頁(yè)上的圖片。
- PNG(.png):一種無(wú)損壓縮格式,支持透明度和更好的圖像質(zhì)量,常用于圖標(biāo)、圖形和需要透明背景的圖片。該圖片是4通道的,外加一個(gè)透明通道。如截屏
- GIF(.gif):一種支持動(dòng)畫(huà)和透明度的格式,常用于簡(jiǎn)單的動(dòng)畫(huà)和圖標(biāo)。
- BMP(.bmp):一種無(wú)損格式,存儲(chǔ)圖像的原始數(shù)據(jù),文件大小通常較大,常用于位圖處理和打印。
- TIFF(.tiff 或 .tif):一種高質(zhì)量的無(wú)損格式,支持多頁(yè)和多種圖像深度,常用于印刷和出版。
除了這些常見(jiàn)的格式,還有其他一些圖片格式,如 WebP、SVG 等,每種格式都有其特定的用途和優(yōu)缺點(diǎn)。
圖片格式之間的轉(zhuǎn)換涉及到通道數(shù)和格式的轉(zhuǎn)換,無(wú)尺寸的變換
2.具體代碼
from PIL import Image
def convert_image(input_path, output_path, output_format):
# 打開(kāi)原始圖片
image = Image.open(input_path)
# 獲取圖片格式
img_format = image.format
# 獲取通道數(shù)
channels = image.mode
# 獲取尺寸
width, height = image.size
# 將JPG圖片轉(zhuǎn)換為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'輸入圖片格式:{img_format}, 輸入圖片的通道數(shù): {channels}, 輸入圖片的尺寸: {(width,height)}')
print("轉(zhuǎn)換完成!")
print(f'輸出圖片格式:{output_image_format}, 輸出圖片的通道數(shù): {image.mode}, 輸出圖片的尺寸: {(width,height)}')
# 設(shè)置輸入圖片路徑
input_image_path = "example.jpg"
# 設(shè)置輸出圖片路徑和格式
output_image_path = "output.png"
output_image_format = "PNG"
# 進(jìn)行圖片格式轉(zhuǎn)換
convert_image(input_image_path, output_image_path, output_image_format)延展:基于Python的圖片格式轉(zhuǎn)換工具
介紹
本教程將指導(dǎo)如何使用 Python 編寫(xiě)的圖片格式轉(zhuǎn)換工具 ImaCon_ter.py,該工具能夠?qū)D片從一種格式轉(zhuǎn)換為另一種格式。支持的格式包括:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。
安裝依賴(lài)
在使用工具之前,請(qǐng)確保已安裝 matplotlib??梢允褂靡韵旅钸M(jìn)行安裝:
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, pgf, 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
'''
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 文件。
打開(kāi)終端:在終端中導(dǎo)航到保存腳本的目錄。
運(yùn)行工具: 使用以下格式運(yùn)行腳本:
python ImaCon_ter.py <filename> <new_format>
例如,將 image.png 轉(zhuǎn)換為 svg 格式:
python ImaCon_ter.py image.png svg
查看結(jié)果:轉(zhuǎn)換完成后,新的圖片文件將與原文件位于同一目錄下,文件名格式為 <原文件名>.<新格式>。
注意事項(xiàng)
確保輸入文件的路徑正確,且文件格式支持轉(zhuǎn)換。
支持的輸出格式有:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。
若遇到任何問(wèn)題,可以查看錯(cuò)誤消息,確保輸入正確,并參考支持的格式列表。
到此這篇關(guān)于python實(shí)現(xiàn)svg圖片轉(zhuǎn)換為png和gif的文章就介紹到這了,更多相關(guān)python svg圖片轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python將Excel轉(zhuǎn)換為多種圖片格式的方法(PNG, JPG, BMP, SVG)
- Python實(shí)現(xiàn)Word文檔轉(zhuǎn)換為圖片(JPG、PNG、SVG等常見(jiàn)格式)
- Python3.7將普通圖片(png)轉(zhuǎn)換為SVG圖片格式(網(wǎng)站logo圖標(biāo))動(dòng)起來(lái)
- Python實(shí)現(xiàn)批量把SVG格式轉(zhuǎn)成png、pdf格式的代碼分享
- Python+PyQt5編寫(xiě)圖片格式轉(zhuǎn)換器
- Python實(shí)現(xiàn)圖片格式轉(zhuǎn)換
- python圖片格式轉(zhuǎn)換腳本
相關(guān)文章
python實(shí)現(xiàn)帶錯(cuò)誤處理功能的遠(yuǎn)程文件讀取方法
這篇文章主要介紹了python實(shí)現(xiàn)帶錯(cuò)誤處理功能的遠(yuǎn)程文件讀取方法,涉及Python使用socket操作遠(yuǎn)程文件的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04
Django中使用CORS實(shí)現(xiàn)跨域請(qǐng)求過(guò)程解析
這篇文章主要介紹了Django中使用CORS實(shí)現(xiàn)跨域請(qǐng)求過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Python實(shí)現(xiàn)生成對(duì)角矩陣和對(duì)角塊矩陣
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)生成對(duì)角矩陣和對(duì)角塊矩陣,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04
Python面經(jīng)之16個(gè)高頻面試問(wèn)題總結(jié)
這篇文章主要給大家介紹了關(guān)于Python面經(jīng)之16個(gè)高頻面試問(wèn)題的相關(guān)資料,幫助大家回顧基礎(chǔ)知識(shí),了解面試套路,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03
python演示解答正則為什么是最強(qiáng)文本處理工具
正則表達(dá)式又稱(chēng)規(guī)則表達(dá)式,通常被用來(lái)檢索、替換那些符合某個(gè)模式(規(guī)則)的文本,它是最強(qiáng)的文本處理工具,至于原因本文將給你答案2021-09-09
Python Pillow庫(kù)詳細(xì)介紹與代碼示例
Python Pillow 庫(kù)是一個(gè)強(qiáng)大的圖像處理工具,是經(jīng)典 PIL(Python Imaging Library)庫(kù)的現(xiàn)代分支,以下是對(duì) Pillow 庫(kù)的全面講解和完整代碼示例,需要的朋友可以參考下2025-04-04
利用Python的裝飾器解決Bottle框架中用戶(hù)驗(yàn)證問(wèn)題
這篇文章主要介紹了Python的Bottle框架中解決用戶(hù)驗(yàn)證問(wèn)題,代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04

