Skip to content

Calling pngtastic from java

Ray Vanderborght edited this page Dec 13, 2016 · 1 revision

Java Usage

Pngtastic can be used as a java library as well as a commandline tool.

The following example shows how to optimize a png image loaded from a file and save the result as a new file.

package example;

import com.googlecode.pngtastic.core.PngImage;
import com.googlecode.pngtastic.core.PngOptimizer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Example pngtastic image optimization usage from java
 */
public class Test {

	public static void main(String[] args) throws Exception {
		// load png image from a file
		final InputStream in = new BufferedInputStream(new FileInputStream("/input.png"));
		final PngImage image = new PngImage(in);

		// optimize
		final PngOptimizer optimizer = new PngOptimizer();
		final PngImage optimizedImage = optimizer.optimize(image);

		// export the optimized image to a new file
		final ByteArrayOutputStream optimizedBytes = new ByteArrayOutputStream();
		optimizedImage.writeDataOutputStream(optimizedBytes);
		optimizedImage.export("/output.png", optimizedBytes.toByteArray());
	}
}
Clone this wiki locally