Edit SVG with Java + Apache Batik to convert to PNG or JPEG

Overview

--Edit SVG with Java + Apache Batik, convert to PNG or JPEG and output --Environment: Apache Batik 1.13 + Java 15 (AdoptOpenJDK 15 + 36) + Gradle 6.6.1

Sample code

build.gradle

Write to run in Gradle. Describe the library to be used.

plugins {
  id 'java'
  id 'application'
}

repositories {
  mavenCentral()
}

dependencies {
  //Apache Batik core module for converting SVG to other formats
  implementation 'org.apache.xmlgraphics:batik-transcoder:1.13'

  //Modules required for PNG and JPEG output
  runtimeOnly 'org.apache.xmlgraphics:batik-codec:1.13'
}

application {
  mainClassName = 'MyApp'
}

MyApp.java

Read and edit SVG files and output as PNG, JPEG, SVG.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.w3c.dom.Element;

// Apache Batik
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.anim.dom.SVGDOMImplementation;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.batik.transcoder.svg2svg.SVGTranscoder;
import org.apache.batik.util.XMLResourceDescriptor;

// Apache XML Commons External Components XML APIs Extensions (xml-apis-ext)
import org.w3c.dom.svg.SVGDocument;

public class MyApp {

  public static void main(String[] args) throws IOException, TranscoderException {

    //Construct a URI from the SVG file path you enter
    URI inputUri = new File("input.svg").toURI();

    //SVGDocument is org.w3c.dom.Interface extending Document
    SVGDocument doc = new SAXSVGDocumentFactory(
      XMLResourceDescriptor.getXMLParserClassName())
      .createSVGDocument(inputUri.toString());

    //It is also possible to edit SVG
    //Let's add a path element here
    Element path = doc.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "path");
    path.setAttribute("id", "foo");
    path.setAttribute("d", "M 1000,2000 h 1000 v 1000 h -1000 z"); //Draw a square
    path.setAttribute("style", "fill: #ff0000; stroke: #0000ff; stroke-width: 100");
    doc.getFirstChild().appendChild(path);

    //Generate input object for conversion
    TranscoderInput input = new TranscoderInput(doc);

    //Output in various formats
    outputPng(input, new File("output.png "));
    outputJpg(input, new File("output.jpg "));
    outputSvg(input, new File("output.svg"));
  }

  //Output in PNG
  private static void outputPng(TranscoderInput input, File outFile) throws IOException, TranscoderException {
    PNGTranscoder t = new PNGTranscoder();
    try (OutputStream os = new FileOutputStream(outFile)) {
      TranscoderOutput output = new TranscoderOutput(os);
      t.transcode(input, output);
    }
  }

  //Output in JPEG
  private static void outputJpg(TranscoderInput input, File outFile) throws IOException, TranscoderException {
    JPEGTranscoder t = new JPEGTranscoder();
    t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, .8f);
    try (OutputStream os = new FileOutputStream(outFile)) {
      TranscoderOutput output = new TranscoderOutput(os);
      t.transcode(input, output);
    }
  }

  //Output as SVG
  private static void outputSvg(TranscoderInput input, File outFile) throws IOException, TranscoderException {
    SVGTranscoder t = new SVGTranscoder();
    try (OutputStream os = new FileOutputStream(outFile)) {
      OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8);
      TranscoderOutput output = new TranscoderOutput(writer);
      t.transcode(input, output);
    }
  }
}

Execution method

Put any input file input.svg in the same directory and run it with gradle run.

$ gradle run

Reference material

Apache Batik

Apache XML Commons External Components XML APIs Extensions

Recommended Posts

Edit SVG with Java + Apache Batik to convert to PNG or JPEG
Convert SVG files to PNG files in Java
How to convert A to a and a to A using AND and OR in Java
Window aggregation of sensor data with Apache Flink and Java 8
Importing Excel data in Java 2
Import Excel data in Java
Implementation of gzip in java
Importing Excel data in Java 3
Implementation of tri-tree in Java
Causes of multiple Singular input data errors in Hull Voronoi 3D
Edit SVG with Java + Apache Batik to convert to PNG or JPEG
How to handle exceptions coolly with Java 8 Stream or Optional
Convert 2D array to csv format with Java 8 Stream API
Convert Java Powerpoint to XPS
Java to play with Function
Connect to DB with Java
Connect to MySQL 8 with Java
How to convert Java radix
[Java] Convert ArrayList to array
Java to learn with ramen [Part 1]
[Java] Points to note with Arrays.asList ()
Convert Markdown to HTML with flexmark-java
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
[Java] Convert 1-to-N List to Map
Java, arrays to start with beginners
[Android] Convert Android Java code to Kotlin
[Java] Convert array to ArrayList * Caution