python實現(xiàn)svg圖片轉(zhuǎn)換為png和gif
python實現(xiàn)svg圖片轉(zhuǎn)換為png和gif
實現(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 時出錯: {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 時出錯: {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實現(xiàn)圖片格式之間的相互轉(zhuǎn)換
1.概要
圖片一般有多種格式,常見的圖片格式包括:
- JPEG(.jpg 或 .jpeg):一種廣泛使用的有損壓縮格式,適用于攝影圖像和網(wǎng)頁上的圖片。
- PNG(.png):一種無損壓縮格式,支持透明度和更好的圖像質(zhì)量,常用于圖標、圖形和需要透明背景的圖片。該圖片是4通道的,外加一個透明通道。如截屏
- GIF(.gif):一種支持動畫和透明度的格式,常用于簡單的動畫和圖標。
- BMP(.bmp):一種無損格式,存儲圖像的原始數(shù)據(jù),文件大小通常較大,常用于位圖處理和打印。
- TIFF(.tiff 或 .tif):一種高質(zhì)量的無損格式,支持多頁和多種圖像深度,常用于印刷和出版。
除了這些常見的格式,還有其他一些圖片格式,如 WebP、SVG 等,每種格式都有其特定的用途和優(yōu)缺點。
圖片格式之間的轉(zhuǎn)換涉及到通道數(shù)和格式的轉(zhuǎn)換,無尺寸的變換
2.具體代碼
from PIL import Image def convert_image(input_path, output_path, output_format): # 打開原始圖片 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" # 進行圖片格式轉(zhuǎn)換 convert_image(input_image_path, output_image_path, output_image_format)
延展:基于Python的圖片格式轉(zhuǎn)換工具
介紹
本教程將指導(dǎo)如何使用 Python 編寫的圖片格式轉(zhuǎn)換工具 ImaCon_ter.py,該工具能夠?qū)D片從一種格式轉(zhuǎn)換為另一種格式。支持的格式包括:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。
安裝依賴
在使用工具之前,請確保已安裝 matplotlib??梢允褂靡韵旅钸M行安裝:
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 文件。
打開終端:在終端中導(dǎo)航到保存腳本的目錄。
運行工具: 使用以下格式運行腳本:
python ImaCon_ter.py <filename> <new_format>
例如,將 image.png 轉(zhuǎn)換為 svg 格式:
python ImaCon_ter.py image.png svg
查看結(jié)果:轉(zhuǎn)換完成后,新的圖片文件將與原文件位于同一目錄下,文件名格式為 <原文件名>.<新格式>。
注意事項
確保輸入文件的路徑正確,且文件格式支持轉(zhuǎn)換。
支持的輸出格式有:eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff。
若遇到任何問題,可以查看錯誤消息,確保輸入正確,并參考支持的格式列表。
到此這篇關(guān)于python實現(xiàn)svg圖片轉(zhuǎn)換為png和gif的文章就介紹到這了,更多相關(guān)python svg圖片轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實現(xiàn)帶錯誤處理功能的遠程文件讀取方法
這篇文章主要介紹了python實現(xiàn)帶錯誤處理功能的遠程文件讀取方法,涉及Python使用socket操作遠程文件的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04Python面經(jīng)之16個高頻面試問題總結(jié)
這篇文章主要給大家介紹了關(guān)于Python面經(jīng)之16個高頻面試問題的相關(guān)資料,幫助大家回顧基礎(chǔ)知識,了解面試套路,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-03-03