I can currently let users load PNG, JPEG, GIF and BMP files into a VM module but it would be nice to add direct support for SVG.
After doing about an hour's worth of research it seems that using a transcoder from Apache Batik is the way to go but I'm wandering how much is involved.
At one level I've found the code shown below which looks really simple but I have no idea how easy it is to set up the build environment for the upper batch of imports.
I know there are a few Java experts here and hopefully you've had experience of installing ASF stuff so any pointers would be handy. Is it straightforward to install the libraries or a major pain? The Apache documentation isn't exactly newbie friendly.
Code: Select all
import lombok.extern.slf4j.Slf4j;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Slf4j
@Component
public class SvgToRasterizeImageConverter {
public BufferedImage transcodeSVGToBufferedImage(File file, int width, int height) {
// Create a PNG transcoder.
Transcoder t = new PNGTranscoder();
// Set the transcoding hints.
t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, (float) width);
t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, (float) height);
try (FileInputStream inputStream = new FileInputStream(file)) {
// Create the transcoder input.
TranscoderInput input = new TranscoderInput(inputStream);
// Create the transcoder output.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(outputStream);
// Save the image.
t.transcode(input, output);
// Flush and close the stream.
outputStream.flush();
outputStream.close();
// Convert the byte stream into an image.
byte[] imgData = outputStream.toByteArray();
return ImageIO.read(new ByteArrayInputStream(imgData));
} catch (IOException | TranscoderException e) {
log.error("Conversion error", e);
}
return null;
}
}