对于svg矢量图的处理,一般可能是存文件形式,但如果只是很少量的,也可直接存数据库:
利用batik既可:
org.apache.xmlgraphics batik-all1.14 pom
import org.apache.batik.anim.dom.SAXSVGdocumentFactory; import org.apache.batik.util.XMLResourceDescriptor; import org.w3c.dom.document; import org.w3c.dom.Element; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.IOException; import java.io.StringWriter; public class SvgUtil { public static String analysisOfSVG(File file) throws IOException { String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGdocumentFactory f = new SAXSVGdocumentFactory(parser); document doc = f.createdocument(file.toURI().toString()); //这里直接获取全部,也可以获取部分 Element element = doc.getdocumentElement(); return transformationSVG(element); } public static String transformationSVG(Element element) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = transFactory.newTransformer(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } StringWriter buffer = new StringWriter(); assert transformer != null; transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); try { transformer.transform(new DOMSource(element), new StreamResult(buffer)); } catch (TransformerException e) { e.printStackTrace(); } return buffer.toString(); } }
doc.getdocumentElement();这里是直接获取了整个所有标签,获取出来大概是这样:(也可以根据名称或者id获取其中某个标签的内容)
当然前后端交互文件一般是MultipartFile。直接转File一下(记得删除临时文件deleteTempFile):
import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.nio.file.Files; import java.util.Objects; public class MultipartFileUtil { public static File multipartFileToFile(MultipartFile file) { File toFile = null; try (InputStream ins = file.getInputStream()) { toFile = new File(Objects.requireNonNull(file.getOriginalFilename())); inputStreamToFile(ins, toFile); } catch (IOException e) { e.printStackTrace(); } return toFile; } private static void inputStreamToFile(InputStream ins, File file) { try (OutputStream os = new FileOutputStream(file)) { int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } ins.close(); } catch (Exception e) { e.printStackTrace(); } } public static void deleteTempFile(File file) throws IOException { Files.delete(file.toPath()); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)