Java batik Operation svg for SVG reading, generation, dynamic operation

Source: Internet
Author: User
Tags naming convention

SVG is still common in today's scenarios, such as drawing complex vector graphics. When it comes to SVG, you cannot mention canvas. Here I will not list the differences between them, and why to choose SVG or canvas.

First of all, my project is a MAVEN project, so I just need to import batik maven dependencies, if it is a normal Java project, you need to find the Jar package import project. Maven dependencies are:

<!-- svg  generate PNG format pictures  --><dependency><groupId>batik</groupId>< artifactid>batik-svggen</artifactid><version>1.6</version></dependency>< dependency><groupid>batik</groupid><artifactid>batik-awt-util</artifactid>< version>1.6</version></dependency><dependency><groupid>batik</groupid>< artifactid>batik-bridge</artifactid><version>1.6</version></dependency>< Dependency><groupid>batik</groupid><artifactid>batik-css</artifactid><version >1.6</version></dependency><dependency><groupid>batik</groupid><artifactid >batik-dom</artifactId><version>1.6</version></dependency><dependency>< Groupid>batik</groupid><artifactid>batik-gvt</artifactid><version>1.6</version ></dependency><dependency><groupiD>batik</groupid><artifactid>batik-parser</artifactid><version>1.6</version> </dependency><dependency><groupid>batik</groupid><artifactid>batik-script</ artifactid><version>1.6</version></dependency><dependency><groupid>batik</ Groupid><artifactid>batik-svg-dom</artifactid><version>1.6</version></dependency ><dependency><groupid>batik</groupid><artifactid>batik-transcoder</artifactid ><version>1.6</version></dependency><dependency><groupid>batik</groupid ><artifactId>batik-util</artifactId><version>1.6</version></dependency>< Dependency><groupid>batik</groupid><artifactid>batik-xml</artifactid><version >1.6</version></dependency><!--  The 2.9.1 version is not available here, using 2.9.1 to generate PNG will fail  --><dependency ><groupid>xerces</groupid><artifactid>xercesimpl</artifactid><version>2.5.0</version></ dependency><dependency><groupid>xml-apis</groupid><artifactid>xmlparserapis</ Artifactid><version>2.0.2</version></dependency><dependency><groupid> org.axsl.org.w3c.dom.svg</groupid><artifactid>svg-dom-java</artifactid><version>1.1 </version></dependency><dependency><groupId>xml-apis</groupId><artifactId> xml-apis</artifactid><version>2.0.0</version></dependency><dependency>< Groupid>org.w3c.css</groupid><artifactid>sac</artifactid><version>1.3</version ></dependency><!-- svg  generate PNG format picture end  -->

This place roughly requires so many jar dependencies, I mainly use batik operation SVG export png or JPG, so the main jar package is batik-transcoder, in fact, as long as the import of this jar package is enough, because the other jar package will be dependent. There are more or less or the wrong, please specify.

Batik working with SVG, first know what Batik did for us:

Batik is a Java-based toolkit for applications and applets that want to use SVG format images for a variety of functions. The purpose of the project creation is to provide developers with a range of core modules that can be combined or used alone to support a particular SVG solution. Modules are mainly svgparser,svggernerator,svgdom. The other purpose of the Batik project is to make it highly scalable-for example, batik allows developers to use custom SVG elements. Even though the goal of the project is to provide a series of core modules, a complete SVG browser is provided to validate the effectiveness and interactivity of each module.

The above remark is a brief overview of the batik on the Batik website. Through this passage we can understand that batik is actually the operation of the SVG is divided into a core module, which mainly includes svgparser (interpreter), Svggernerator (generator), Svgdom (DOM element). By literal means we can know what the main core modules of batik have done for us. Svgparser interpreter is mainly for SVG XML file node parsing, svggernerator (generator) can generate an SVG file, Svgdom can establish Svgdom node, and add different attributes on each element.    

With batik, you can manipulate SVG documents anywhere you use Java.     You can also use various batik modules to generate, manipulate and convert your SVG images in your applications and applets. Batik makes it easy to process SVG content through Java. For example, by using the Batik svggernerate module, Java applications and applets can be very simple to format the output image as SVG. With Batik's SVG viewing component, applications or applets can easily integrate SVG viewing and interactivity. You can also use the Batik module to convert SVG to other formats, such as JPEG image formats and other vector formats such as PDFs.

The above remark is also the official website batik to Batik's one use explanation. First we choose a language, or a technology, we must know what we want to do, the technology or tools can meet their own needs, can solve the existing problems. Choose a good technology, not in a hurry to take the code with, but first to understand it slowly, I admit, I do not know batik, even said to it is not known. Because I just stay on the level that uses it. But we can use dots to line the screen.

Paste the code First, then explain:

public class svgpngconverter {    /**     *  Batik by reading the SVG file png     *  @param  filePath  incoming read SVG file       *  @param  pngFilePath  converted PNG pictures      *  @param  map  changing the collection of SVG properties   pass-through rules,id,name,value  mainly changes the color attribute values of the SVG child nodes.      *  If you need to change the color properties of multiple element in SVG   The naming convention is  id1,name1,value1,id2,name2, Value2 .... Analogy      *  @throws  IOException     *  @throws  transcoderexception     */    public static void  converttopngbyfile (string filepath, string pngfilepath,map<string, string>  map) Throws ioexception, transcoderexception {file file = new file ( pngFilePath); fileoutputstream outputstream =  Null;try {file.createnewfile (); Outputstream = new fileoutputstream (file); Converttopngbyfile (FILEPATH,&NBSP;OUTPUTSTREAM,MAP);}  finally {if  (Outputstream != null)  {try {outputstream.close ();}  catch  (ioexception e)  {e.printstacktrace ();}}}         public static void converttopngbyfile (String &NBSP;PATH,&NBSP;OUTPUTSTREAM&NBSP;OUTPUTSTREAM,MAP&LT;STRING,&NBSP;STRING&GT;&NBSP;MAP)              throws transcoderexception, ioexception {         try {        file  file = new file (path);         string parser  = xmlresourcedescriptor.getxmlparserclassname (); Saxsvgdocumentfactory f = new saxsvgdocumentfactory (parser);D OcumEnt doc = f.createdocument (File.touri (). toString ());for  (int i = 1; i  <=map.size ()/3; i++)  {element e = doc.getelementbyid (Map.get ("id" +i)); System.out.println (Map.get ("name" +i)) E.setattribute (Map.get ("name" +i),  map.get ("value" +i));             pngtranscoder t = new  pngtranscoder ();             transcoderinput  input = new transcoderinput (DOC);             transcoderoutput output = new transcoderoutput (OutputStream);             t.transcode (input, output);             outputstream.flush ();         } finally {            if  (outputStream !=  NULL)  {                 try {                     outputstream.close ();                 } catch  (ioexception e)  {                      E.printstacktrace ();                 }            }         }    }}

With the code above, I can see that I'm going to export an SVG to a PNG formatted image and output it. First of all, the above method is just to create a file, just enter the address of the image to be exported, as well as the SVG file address to read, the next map parameter is mainly for the back operation of SVG DOM elements prepared, and later. The next method is to create a file stream at the beginning, which is used to read the SVG file, the latter three sections of the code is to create a DOM element from an SVG, which means to convert the read SVG file into a Document object that has the contents of all element nodes in the incoming SVG file. Here is a loop, which I mainly do by defining the key value of the map, mainly into the Id,svg node properties (also can be DOM elements, such as Style,class), and finally the value of the node properties. This allows us to control element elements of the document object to achieve the purpose of dynamically changing the SVG content. Batik can convert an SVG to PNG, mainly Pngtranscoder Transcode method is done, specifically how to complete we do not need to go to the relationship, here we only care about what the parameters it needs, the first parameter is the Transcoderinput object, This object needs to pass in a value, and the way I do it is to pass in a Svgdocument object, because we need to dynamically change the properties of the original SVG file and generate the changed PNG image. If you don't need to dynamically change the output of SVG, you just have to stream the incoming SVG file into the Transcoderinput object, which can be well understood by looking at the API of the Batick Transcoderinput class. The second parameter is the Transcoderoutput object, the name of the object we know what it does, and it requires a stream of previously created output images that were passed in. Finally, the Transcode method converts SVG to PNG.

The above code is just a simple application of the SVG conversion image of the core module function, batik there are many core function modules I do not use, but the common usage is that a little bit above, I hope to be a little help to the people just contact.


Java batik Operation svg for SVG reading, generation, dynamic operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.