Exemple #1
0
def generate_svg():

	try:
		x = int(request.args.get('x'))
		y = int(request.args.get('y'))
		bg_color = request.args.get('bg_color')
		cross_color = request.args.get('cross_color')
		if bg_color is not None and cross_color is not None:
			bg_color = "#" + str(request.args.get('bg_color'))
			cross_color = "#" + str(request.args.get('cross_color'))
			svg = SVG(x=x, y=y, background_color=bg_color, cross_color = cross_color)
		elif bg_color is not None:
			bg_color = "#" + str(request.args.get('bg_color'))
			svg = SVG(x=x, y=y, background_color=bg_color)
		elif cross_color is not None:
			cross_color = "#" + str(request.args.get('cross_color'))
			svg = SVG(x=x, y=y, cross_color=cross_color)
		else:
			svg = SVG(x=x, y=y)

		return svg.create().min_svg(), 200
	except Exception, e:
		return 'something went wrong!\nTry /img?x=10&y=10&bg_color=ff0000&cross_color=00ff000', 404
Exemple #2
0
 def create_svg_code(self, array, filename, format_string, version):
     svg = SVG()
     cell_size = 20
     svg_size = cell_size * (len(array) + 8)
     svg.prep_for_drawing(svg_size, svg_size)
     length = (4 * version) + 17
     # Bottom right format information
     br = [[x, 8] for x in range(length - 1, length - 9, -1)]
     br += [[8, y] for y in range(length - 7, length, 1)]
     for i in range(len(br)):
         x = br[i][0]
         y = br[i][1]
         if(format_string[i] == '1'):
             svg.add_coloured_rect(x*20, y*20, 'rgb(0, 0, 0);')
     # Top left format information.
     tl = [[8, y] for y in range(0,9)]
     tl += [[x, 8] for x in range(7,-1,-1)]
     c = 0
     for i in range(len(tl)):
         x = tl[i][0]
         y = tl[i][1]
         if not ((x == 6 and y == 8) or (x == 8 and y == 6)):
             if(format_string[c] == '1'):
                 svg.add_coloured_rect(x*20, y*20, 'rgb(0, 0, 0);')
             c+=1
     for x in range(len(array)):
         for y in range(len(array[x])):
             if(array[x][y]) == 1:
                 svg.add_rect(x*20, y*20)
     svg.save(filename + '.svg')
# a

if (len(sys.argv) < 3):
    print(
        "function requires an input filename, number of colours, stitch count and mode"
    )
    sys.exit(0)

input_file_name = sys.argv[1]  # input file name, has to be a jpg
num_colours = int(sys.argv[2])  # number of colours to use in the pattern
count = int(sys.argv[3])  # stitch count, number of stitches in x axis

# black_white, minor, symbols

col_sym = SVG(False, True, True)
blw_nsy = SVG(True, True, True)
col_nsy = SVG(False, False, False)
key = SVG(False, True, True)

# b

im = Image.open(input_file_name)

# c

new_width = 1000
pixelSize = int(new_width / int(count))
new_height = int(new_width * im.size[1] / im.size[0])
im = im.resize((new_width, new_height), Image.NEAREST)
Exemple #4
0
 
 term_name_pos = []
 fp = open(section_name + '-text', 'r')
 for line in fp.readlines():
     m, t = line.strip('\n').split('   ')
     m = m.strip('matrix()').split()
     m = [float(n) for n in m]
     x = m[4] * 1.25
     y = m[5] * 1.25
     term_name_pos.append((t, x, y))
 fp.close()
 
 buf = ''
 for i in range (1, svg_num):
     #print i
     svg = SVG.open(section_name + '/' + str(i) + '.svg')
     svg.load()
     svg.collect('path', 'd')
     
     path = svg.data['path'][0]
     segs = seg_ptn.findall(path)
     cursor = None
     
     paths = []
     for seg in segs:
         cmd = seg[0]
         if cmd in ['Z', 'z']:
             path.close()
             cursor = path.start
         else:
             nums = num_ptn.findall(seg.strip(' MmLlHhVvCcSsQqTtAaZz'))
Exemple #5
0
    def startBuildUp(self):
        if self.options['width'] < 1 or self.options['height'] < 1:
            print 'Invalid output pixel --height or --width specified.'
        if zero(self.options['zoom']) or self.options['zoom'] < 0:
            print 'Zoom limiting value is invalid; must be positive.'
        if self.options['xx']:
            self.options['from'] = self.options['until'] = -1
        if self.options['fullpath']:
            self.options['path'] = True

        # overall preparations
        overall = time.time()

        folder_name = [ self.options['folder'], self.options['name'] ]
        
        if not os.path.exists(self.filename):
               print 'SVG files were not found.'
        else:
            fileBaseName = os.path.splitext(os.path.basename(self.filename))
#            print fileBaseName
            if folder_name[0] == 'movie':
                self.options['folder'] = fileBaseName[0]
            self.options['name'] = fileBaseName[0]
            
            if self.options['page']:
                self.options['folder'] += '_page'
            if self.options['backward']:
                self.options['folder'] += '_backward'

            if not os.path.exists(self.options['folder']):
                os.mkdir(self.options['folder'])
                
            start = time.time()
            self.printText.emit('Starting buildup of %s...' % self.filename)
            
            try:
                self.svg = SVG()
                elementCount = self.svg.read(str(self.filename))

                if self.options['page']:
                    self.options['width'] = self.svg.root.attrib['width']
                    self.options['height'] = self.svg.root.attrib['height']

            except Exception as e:
                print 'error'
                self.finished.emit()
                return
            
            if self.options['fullpath']:
                defs_element = self.svg.root.find('{http://www.w3.org/2000/svg}defs')
                markers = defs_element.findall('{http://www.w3.org/2000/svg}marker')
                
                if len(markers) == 0:
                    self.addMarker(defs_element, self.options['marker'])
                else:
                   self.marker = '%s' % markers[0].attrib['id']

            self.printText.emit('Surveyed %d elements.' % elementCount)
            
            self.camera = Camera(self.options)
            self.camera.printText.connect(self.printText)
#            self.finished.emit()
#            return 0
            
            if self.camera.survey(self.svg):
                #self.printText.emit('ok')
                self.camera.move(self.svg.root.attrib['id'])
                self.build(self.svg, self.camera, self.svg.root, self.options)
                
                if self.isRunning:
                    self.printText.emit('Finishing...')
                    self.options['camera'] = False
                    self.camera.shoot(self.svg)
                    self.camera.hold(self.options['hold'])
                    self.camera.cleanup()
                else:
                    self.printText.emit('Canceled...')
            
            finish = time.time()
            hours = int((finish - start) / 60) / 60
            minutes = int((finish - start) / 60) % 60
            folder = self.options['folder']
            self.printText.emit('Finished %s to %s in %dh:%02dm.' % (self.filename, folder, hours, minutes))
            
        self.finished.emit()
Exemple #6
0
class SVGBuild(QtCore.QObject):    
    finished = QtCore.pyqtSignal()
    canceled = QtCore.pyqtSignal()
    printText = QtCore.pyqtSignal(QtCore.QString)
    
    svg = SVG()
    options = { 'folder': 'movie',
            'name': 'movie',
            'temp': 'temp.svg',
            'from': 0,
            'until': 99999,
            'image': False,
            'path': False,
            'fullpath': False,
            'fillpath': False,
            'closepath': False,
            'top': False,
            'page': False,
            'combine': False,
            'camera': False,
            'line' : '#000000',
            'frame' : '#FF0000',
            'text': False,
            'backward': False,
            'width': 640,
            'height': 480,
            'dally': 4,
            'dolly': 50,
            'hold': 100,
            'background': '#FFFFFF',
            'zoom': 6.,
            'xx': False
            }
            
    isRunning = False
    
    def __init__(self):
        super(SVGBuild, self).__init__()
        #self.camera = Camera(self.options)
        
    def setFilename(self, filename):
        self.filename = filename
        
    def setIsRunning(self,  isRunning):
        self.isRunning = isRunning
        
        if not isRunning:
            self.camera.setIsRunning(isRunning)
            self.canceled.emit()
        
    def getOptions(self):
        return self.options
        
    def setSingleOption(self, key,  value):
        self.options[key] = value
        
    def getSingleOption(self, key):
        return self.options[key]
        
    def getPathOption(self):
        return self.getSingleOption('path')
        
    def getFullPathOption(self):
        return self.getSingleOption('fullpath')
        
    def getCameraOption(self):
        return self.getSingleOption('camera')
        
    def getPageOption(self):
        return self.getSingleOption('page')
    
    def startBuildUp(self):
        if self.options['width'] < 1 or self.options['height'] < 1:
            print 'Invalid output pixel --height or --width specified.'
        if zero(self.options['zoom']) or self.options['zoom'] < 0:
            print 'Zoom limiting value is invalid; must be positive.'
        if self.options['xx']:
            self.options['from'] = self.options['until'] = -1
        if self.options['fullpath']:
            self.options['path'] = True

        # overall preparations
        overall = time.time()

        folder_name = [ self.options['folder'], self.options['name'] ]
        
        if not os.path.exists(self.filename):
               print 'SVG files were not found.'
        else:
            fileBaseName = os.path.splitext(os.path.basename(self.filename))
#            print fileBaseName
            if folder_name[0] == 'movie':
                self.options['folder'] = fileBaseName[0]
            self.options['name'] = fileBaseName[0]
            
            if self.options['page']:
                self.options['folder'] += '_page'
            if self.options['backward']:
                self.options['folder'] += '_backward'

            if not os.path.exists(self.options['folder']):
                os.mkdir(self.options['folder'])
                
            start = time.time()
            self.printText.emit('Starting buildup of %s...' % self.filename)
            
            try:
                self.svg = SVG()
                elementCount = self.svg.read(str(self.filename))

                if self.options['page']:
                    self.options['width'] = self.svg.root.attrib['width']
                    self.options['height'] = self.svg.root.attrib['height']

            except Exception as e:
                print 'error'
                self.finished.emit()
                return
            
            if self.options['fullpath']:
                defs_element = self.svg.root.find('{http://www.w3.org/2000/svg}defs')
                markers = defs_element.findall('{http://www.w3.org/2000/svg}marker')
                
                if len(markers) == 0:
                    self.addMarker(defs_element, self.options['marker'])
                else:
                   self.marker = '%s' % markers[0].attrib['id']

            self.printText.emit('Surveyed %d elements.' % elementCount)
            
            self.camera = Camera(self.options)
            self.camera.printText.connect(self.printText)
#            self.finished.emit()
#            return 0
            
            if self.camera.survey(self.svg):
                #self.printText.emit('ok')
                self.camera.move(self.svg.root.attrib['id'])
                self.build(self.svg, self.camera, self.svg.root, self.options)
                
                if self.isRunning:
                    self.printText.emit('Finishing...')
                    self.options['camera'] = False
                    self.camera.shoot(self.svg)
                    self.camera.hold(self.options['hold'])
                    self.camera.cleanup()
                else:
                    self.printText.emit('Canceled...')
            
            finish = time.time()
            hours = int((finish - start) / 60) / 60
            minutes = int((finish - start) / 60) % 60
            folder = self.options['folder']
            self.printText.emit('Finished %s to %s in %dh:%02dm.' % (self.filename, folder, hours, minutes))
            
        self.finished.emit()
        
    def build(self, svg, camera, entity, options):
        '''Recursively build up the given entity, by removing all its children
        and adding them back in one at a time, and shooting the progress with
        the given camera.
        '''
        
        if not self.isRunning: return

        id = entity.attrib['id']
        name = id
        label = 'http://www.inkscape.org/namespaces/inkscape}label'
        if label in entity.attrib:
            name = entity.attrib[label]
        print '%05d - Building up <%s id="%s"> (%s)...' % (camera.time, entity.tag, id, name)
        self.printText.emit('%05d - Building up <%s id="%s"> (%s)...' % (camera.time, entity.tag, id, name))

        nobuild = set([ '{http://www.w3.org/2000/svg}defs',
                        '{http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd}namedview',
                        '{http://www.w3.org/2000/svg}metadata',
                        ])

        nochild = set([ '{http://www.w3.org/2000/svg}text',
                        ])

        backable = set([ '{http://www.w3.org/2000/svg}svg',
                         '{http://www.w3.org/2000/svg}g',
                        ])

        ripped = [ ]
        for child in entity.iterchildren():
            if child.tag in nobuild: continue
            if not child.attrib['id'] in camera.layout: continue
            if 'style' in child.attrib:
                if 'display:none' in child.attrib['style']:
                    continue
            ripped.append(child)
        for child in ripped:
            entity.remove(child)

        backward = False    
        
        '''build from the lowest object'''
        if entity.tag in backable and self.options['backward']:
            backward = True
        
        '''build from the top object'''
        if backward:
            self.printText.emit(' (Building children of entity %s backwards.)' % id)
            #print ' (Building children of entity %s backwards.)' % id
            ripped.reverse()

        for child in ripped:
            if not self.isRunning: return
            self.printText.emit(' Adding child <%s id="%s">...' % (child.tag, child.attrib['id']))
            #print ' Adding child <%s id="%s">...' % (child.tag, child.attrib['id'])
            
            if self.options['page']:
                if self.options['camera']:
                    camera.pan(svg, child.attrib['id'], margin=1.2)

                camera.shoot(svg)
            else:
                camera.pan(svg, child.attrib['id'], margin=1.2)

            if child.getchildren() and not child.tag in nochild:
                if backward:
                    entity.insert(0, child)
                else:
                    entity.append(child)

                self.build(svg, camera, child, options)
            else:
                if self.options['top']:
                    svg.root.append(child)
                else:
                    if backward:
                        entity.insert(0, child)
                    else:
                        entity.append(child)

                if self.options['path'] and re.search(r"\}path$", child.tag):
                    self.build_path(svg, camera, child, options)
                elif self.options['image'] and re.search(r"\}image$", child.tag):
                    self.build_image(svg, camera, child, options)
                elif self.options['text'] and re.search(r"\}text$", child.tag):
                    self.build_text(svg, camera, child, options)
                else:
                    camera.shoot(svg)

                if self.options['top']:
                    svg.root.remove(child)
                    if backward:
                        entity.insert(0, child)
                    else:
                        entity.append(child)

            camera.shoot(svg)
            camera.hold(self.options['dally'] - 1)

        camera.pan(svg, id)
        
    def build_image(self, svg, camera, entity, options):
        '''Special progressive drawing of an image element.
        The image will be included a few scanlines at a time until whole.'''
        
        if not self.isRunning: return
        
        href = '{http://www.w3.org/1999/xlink}href'
        if not href in entity.attrib: return
        img_url = urlparse.urlparse(entity.attrib[href])
        img = img_url.path
        if not os.path.exists(img):
            print 'Image file not found locally:', img
            return
        # figure out original image's pixel size
        '''results = Utils.qx('%s %s' % (str(Settings.identify), img))
        m = re.search(r'(\d+)x(\d+)', results)
        if not m:
            print 'ImageMagick could not identify size of image; skipping.'
            return'''
        try:
            output_image = Image.open(img)
        except IOError, e:
            print "error opening file :: %s" % img
        size = output_image.size
        # for a handful of frames, replace image with a truncated temporary image
        tmp = self.options['folder'] + '/temp.png'
        frames = int(self.options['dally']) * 4
        for frame in range(frames):
            height = interpolations.linear(0, frames, frame, 1, size[1])
            box = (0, 0, size[0], height)
            area = output_image.crop(box)
            background = Image.new("RGBA", size)
            background.paste(area,box)
            background.save(tmp, 'PNG')
            
            if os.path.exists(tmp):
                entity.attrib[href] = tmp
                camera.shoot(svg)
                os.unlink(tmp)
        # replace the original image reference
        entity.attrib[href] = img
        camera.shoot(svg)
Exemple #7
0
        "124",
        "125",
        "126",
        "127",
        "128",
        "129",
        "130",
        "131",
        "132",
    ]

    for section_num in SECTION_NUMS[1:]:
        section_name = ROOT_PATH + FILE_NAME_PREFIX + section_num + "BW"
        print section_name

        svg = SVG.open(section_name + ".svg")
        svg.load()
        svg.collect2("path", "d")
        # svg.collect2('text', 'transform')

        fp = open(section_name + "-path", "w")
        for i in svg.data["path"]:
            fp.write(i + "\n")
        fp.close()

        # fp = open(section_name + '-text', 'w')
        # for i in svg.data['text']:
        #    fp.write(i + '\n')
        # fp.close()

        paths = get_paths(section_name + "-path")
from SVG import SVG
from Raster import Rasterizer
from CoordinateTrace import CoordinateTrace
from MotorStep import MotorStep

if __name__ == "__main__":

    svg = SVG(200, 30)
    rasterizer = Rasterizer()

    while True:

        file = input('Input file: ')
        input_type = file.split('.')[1]

        if input_type not in ['svg', 'jpg', 'ct']:
            print('Error: Invalid input type.')
            continue

        output = input('Export as (.ct/.mstp): ')
        output_name = output.split('.')[0]
        output_type = output.split('.')[1]

        if output_type not in ['ct', 'mstp']:
            print('Error: Invalid output type.')
            continue

        if '/' in output_name:
            print('Error: Name cannot contain paths.')
            continue