Quantcast
Channel: Lucee Dev - Latest topics
Viewing all articles
Browse latest Browse all 549

Demo: Rendering SVG using Batik with Lucee 6.2

$
0
0

Another quick demo of using the new Java Integration in Lucee 6.2

No more messing around with downloading jars and paths, just pure cfml!

<cfscript>
svgRender = new component javasettings='{
	maven: [
		"org.apache.xmlgraphics:batik-transcoder:1.18",
		"org.apache.xmlgraphics:batik-codec:1.18"
		]
	}'
{
	import java.io.FileInputStream;
	import java.io.FileOutputStream;
	import java.io.File;
	import org.apache.batik.transcoder.TranscoderInput;
	import org.apache.batik.transcoder.TranscoderOutput;
	import org.apache.batik.transcoder.image.PNGTranscoder;
	import org.apache.batik.transcoder.image.JPEGTranscoder;

	public function render(required string svgPath,
			required string outputPath,
			string format = "PNG") {
		var transcoder = createTranscoder(format);		
		var input = new TranscoderInput(new FileInputStream(new File(svgPath)));
		var outputStream = new FileOutputStream(outputPath);
		try {
			var output = new TranscoderOutput(outputStream);
			transcoder.transcode(input, output);
			outputStream.flush();
		} catch(e) {
			rethrow;
		} finally {
			outputStream.close();
		}
	}
	function createTranscoder(required string format, input) {
		switch(format.ucase()) {
			case "PNG":
				return new PNGTranscoder();
			case "JPG":
			case "JPEG":
				var transcoder = new JPEGTranscoder();
				// use static syntax to access properties
				// cast the quality to float as arg is object and can't be determined
				transcoder.addTranscodingHint(JPEGTranscoder::KEY_QUALITY, javaCast("float","0.1"));
				return transcoder;
			default:
				throw("Unsupported format: #format#");
		}
	}
}

dump(var=deserializeJson( getMetaData( svgRender ).javasettings ), 
label="javaSettings");

svgSrc = "https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg";
// dir is now optional with named parameters in 6.2, it defaults to getTempDiretory()
svgFile = getTempFile( prefix="svg", ext="svg" );

http url=svgSrc file=svgFile;
echo( htmlcodeformat( fileRead( svgFile ) ) );

imgFile = getTempFile( prefix="jpg", ext="jpg" ); 
svgRender.render( svgFile, imgFile, "jpg" );
ImageWriteToBrowser( imgFile );

imgFile = getTempFile( prefix="png", ext="png" );
svgRender.render( svgFile, imgFile, "png" );
ImageWriteToBrowser( imgFile );

</cfscript>

You can also preload these jars using MavenLoad() otherwise Lucee will dynamically download them as required

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 549

Latest Images

Trending Articles



Latest Images