失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java svg to png_如何用Image Magick将SVG转换为PNG?

java svg to png_如何用Image Magick将SVG转换为PNG?

时间:2020-11-29 08:26:42

相关推荐

java svg to png_如何用Image Magick将SVG转换为PNG?

我已经通过更改 标签的 width 和 height 属性以匹配我的预期输出大小然后使用ImageMagick进行转换来解决了这个问题 . 奇迹般有效 .

这是我的Python代码,一个将返回JPG文件内容的函数:

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

如果觉得《java svg to png_如何用Image Magick将SVG转换为PNG?》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。