How to convert a SVG to a PNG with ImageMagick?

前端 未结 18 2132
一个人的身影
一个人的身影 2020-11-28 17:04

I have a SVG file that has a defined size of 16x16. When I use ImageMagick\'s convert program to convert it into a PNG, then I get a 16x16 pixel PNG which is way too small:<

18条回答
  •  情话喂你
    2020-11-28 17:48

    I've solved this issue through changing the width and height attributes of the tag to match my intended output size and then converting it using ImageMagick. Works like a charm.

    Here's my Python code, a function that will return the JPG file's content:

    import gzip, re, os
    from ynlib.files import ReadFromFile, WriteToFile
    from ynlib.system import Execute
    from xml.dom.minidom import parse, parseString
    
    
    def SVGToJPGInMemory(svgPath, newWidth, backgroundColor):
    
        tempPath = os.path.join(self.rootFolder, 'data')
        fileNameRoot = 'temp_' + str(image.getID())
    
        if svgPath.lower().endswith('svgz'):
            svg = gzip.open(svgPath, 'rb').read()
        else:
            svg = ReadFromFile(svgPath)
    
        xmldoc = parseString(svg)
    
        width = float(xmldoc.getElementsByTagName("svg")[0].attributes['width'].value.split('px')[0])
        height = float(xmldoc.getElementsByTagName("svg")[0].attributes['height'].value.split('px')[0])
    
        newHeight = int(newWidth / width * height) 
    
        xmldoc.getElementsByTagName("svg")[0].attributes['width'].value = '%spx' % newWidth
        xmldoc.getElementsByTagName("svg")[0].attributes['height'].value = '%spx' % newHeight
    
        WriteToFile(os.path.join(tempPath, fileNameRoot + '.svg'), xmldoc.toxml())
        Execute('convert -background "%s" %s %s' % (backgroundColor, os.path.join(tempPath, fileNameRoot + '.svg'), os.path.join(tempPath, fileNameRoot + '.jpg')))
    
        jpg = open(os.path.join(tempPath, fileNameRoot + '.jpg'), 'rb').read()
    
        os.remove(os.path.join(tempPath, fileNameRoot + '.jpg'))
        os.remove(os.path.join(tempPath, fileNameRoot + '.svg'))
    
        return jpg
    

提交回复
热议问题