In this tutorial, we will explain with an example on how to convert a PNG image format to JPG format, by using JMagick Java library. We have earlier discussed handling BMP to JPG / PNG compression using the same library. We will use 123kb input PNG image file for doing the conversion.
Download JMagick
To work with the example provided in this tutorial, you have to download a copy of the jmagick.jar file. This is available at this link. Make sure you have loaded this JAR file into your classpath.
PNG Image Size
You can use any test PNG image for this conversion. The one that I used is 123 Kb.
JMagick Example – PNG to JPG
The complete Java code that converts PNG to JPG using JMagick library is provided below:
import magick.ImageInfo;
import magick.MagickImage;
public class jmagick_png_jpg {
public static void main(String[] args) throws Exception {
//Read input PNG image
String inputfileName = "input_png.png";
//Read image into ImageInfo object
ImageInfo info = new ImageInfo(inputfileName);
//Create MagickImage that converts format
MagickImage magick_converter = new MagickImage(info);
//Specify output file name
String outputfile = "jmagick_png2jpg.jpg";
//Set output format
magick_converter.setFileName(outputfile);
//Write JPG file
magick_converter.writeImage(info);
}
}
Interestingly, the output image file size in my case came to 170 Kb. You can always set different options to your output image file (like, down sampling, resizing etc) to suit to your needs. JMagick library has rich set of methods available to perform the conversion to your needs.
That completes a quick tutorial on PNG to JPG conversion in JMagick. In the next tutorial, we will discuss how to do the same conversion using ImageIO library.
No comments:
Post a Comment