Welcome! Log In Create A New Profile

Advanced

SVG to GIF converter

Posted by Kalium 
SVG to GIF converter
November 02, 2015 09:10AM
Hi all,
I'm quite new of this forum. Few days ago I started to consider DLP printers. Some of the software couldn't read directly the SVG file produced by slic3r, so I decided to write a small piece of Python code to do that.
I hope that someone might be interested in this.
The program is very simple and produces images 700x700 pixels maximum.
from Tkinter import*
from PIL import ImageTk, Image, ImageDraw
import Tkinter
import threading
import tkMessageBox
import tkFileDialog
from os import listdir


#Common Variables
counter = 0
running = 0
height = width = 0
lines = []
layerstart = []
layercount = 0
filename = ''

#Base window
base = Tk()
F = Frame(base, relief="sunken", border=1)
F.pack(side="left", fill="y")
G = Frame(F, relief="groove")
G.pack(side="bottom", fill="y")
IM = Frame (base, relief = "flat", bg ="black")
IM.pack(expand="true", fill = "both")


#Functions
def LoadSVG():
   global filename,lines,layerstart,layercount,height,width
   del lines[:]
   del layerstart[:]
   filename = tkFileDialog.askopenfilename(filetypes = [('SVG files', '.SVG')])
   lines = [line.rstrip('\n') for line in open(filename)]
   layercount = 0
   for index in range(len(lines)):
      thisline=lines[index]
      if "layer" in thisline:
         layercount = layercount + 1
         layerstart.append(index)
      if "width" in thisline:
         w1=thisline.find('width="')
         w2=thisline.find('"', w1+7)
         width=float(thisline[w1+7:w2])
         print 'width: ',width
         h1=thisline.find('height="')
         h2=thisline.find('"', h1+8)
         height=float(thisline[h1+8:h2])
         print 'height: ', height
         
   layerstart.append(len(lines))      
   #print layerstart
   print "layers found: ",layercount
   eLayerNum.delete(0, END)
   eLayerNum.insert(0, layercount)
    
def start():
   global filename,running,counter
   if len(filename) == 0:
     tkMessageBox.showerror("ERROR", "Load SVG first") 
     return 
   if running == 0:
       running = 1
       counter = 0
       threading.Timer(0.1, ConvertIt).start()
   else:
      running=0
      print "Process stopping"
      pg.set("STOPPED")

def formatstr(number):
   temp=str(number)
   while len(temp)<4:
      temp='0'+temp
   return temp   
      
def DrawLayer(currentlayer,saveimage):
   global filename,lines,layerstart,layercount   
   if (currentlayer<1) | (currentlayer>layercount):
      return
   if saveimage==TRUE:
      image1 = Image.new("RGB", (700, 700), 'black')
      draw = ImageDraw.Draw(image1)
   w.delete(ALL)
   pixels=int(eHeight.get())
   scale=pixels/height
   yoffset=int((700-pixels)/2)
   xoffset=int((700-(width*scale))/2)
   polygons=0
   startline=layerstart[currentlayer-1]
   endline=layerstart[currentlayer]
   for l in range(startline,endline):
      line = lines[l] 
      if "polygon" in line:
         if "white" in line:
            fcolor='white'
         else:
            fcolor='black'
         polygons+=1
         mylist = line.split("points=")
         mylist = mylist[1].split('"')
         mylist = mylist[1].split(" ")
         my_points = []
         for x in mylist:
            pts = x.split(",")
            my_points.append(float(pts[0])*scale+xoffset)
            my_points.append(float(pts[1])*scale+yoffset)
         w.create_polygon(my_points, fill=fcolor)
         if saveimage==TRUE:
            draw.polygon(my_points, fill=fcolor)
   if saveimage==TRUE:
      fname=filename[:filename.find('.')]+formatstr(currentlayer)+'.gif'
      print 'saving: '+fname
      image1.save(fname)      
   print "layer ",currentlayer," polygons found: ",polygons      

def ConvertIt():
  global counter,running
  if running == 1:
   counter=counter+1
   if counter > layercount:
      running=0
      pg.set('Conversion\nFinished')
   else:
      DrawLayer(counter,TRUE)
      pg.set(str(counter)+'/'+str(layercount))
      threading.Timer(0.1, ConvertIt).start()
   
def Show():
   currentlayer=int(elayer.get()) #get the layer to show
   DrawLayer(currentlayer,FALSE)
      
#Canvas definition
w = Tkinter.Canvas(IM, width=700, height=700, bg="black", relief="ridge", highlightthickness=0)
w.pack(expand="true")


#Labels
lSvg2gif = Label(F, text="SVG to GIF", padx=5, pady=5)
lSvg2gif.pack(side="top")

lShowlayer = Label(G, text="SHOW LAYER", padx=5, pady=5)
lShowlayer.pack(side="top")

#Title
F.master.title("Slic3r SVG file viewer / converter")


#Buttons
bStart = Button(F, text="START/STOP", command=start)
bStart.pack(side="top", padx=10, pady=10)
bLoad = Button(F, text="Load SVG", command=LoadSVG)
bLoad.pack( padx=10, pady=10)
bShow = Button(G, text="SHOW", command=Show)
bShow.pack(side="bottom", padx=2, pady=2)

#Entries
lHeight = Label(F, text="Height (pixels)")
lHeight.pack()
eHeight = Entry(F)
eHeight.insert(0, 300)
eHeight.pack()

llayer = Label(F, text="Number of layers")
llayer.pack()
eLayerNum = Entry(F)
eLayerNum.insert(0, 0)
eLayerNum.pack()

pg=StringVar() 
lProgress = Label(F, textvariable=pg, fg="red", font="Verdana 10 bold")
lProgress.pack(padx=10, pady=10)

elayer = Entry(G)
elayer.insert(0, 1)
elayer.pack(padx=5, pady=5)



#Activate
base.mainloop()

Sorry, only registered users may post in this forum.

Click here to login