This examples show how to convert svg files to png files with white background or transparent background. You can convert single file, you can also convert many files together quickly. Create a file which includes all svg file names, and create a file which includes all output png file names. It’s better put the svg files and the png files in different directories.
Code examples:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
from PIL import Image
import pandas as pd
#---------------------------------------
path0='svgfile_path/'
svgfile='svgfiles.txt'
fullpath=path0+svgfile
svgfns=pd.read_csv(fullpath)
svgfns.tail
#---------------------------------------
# convert svg file to png file with white background
for svgfn in svgfns.FileName:
toopen=path0+svgfn
towrite='Selman_png/'+svgfn
towrite=towrite.replace('.svg','.png')
drawing = svg2rlg(toopen)
renderPM.drawToFile(drawing, towrite, fmt='PNG',bg=None)
#-----------------------------------------------------------
#convert svg file to png file with transparent background
for svgfn in svgfns.FileName:
toopen=path0+svgfn
towrite='pngfile_path/'+svgfn #the svg file
towrite=towrite.replace('.svg','.png') #the png file
# Import the image
file_name = towrite
img = Image.open(file_name)
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
transparentpng=towrite.replace('pngfile_path','transparent_pngfile_path')
img.save(transparentpng, "PNG")