Gaurav K Gaurav K - 1 month ago 9
Java Question

Saving an image to .jpg file : Java

The way I am saving a jFreeChart to a jpeg file is :

JFreeChart chart = ChartFactory.createXYLineChart(
"Hysteresis Plot", // chart title
"Pounds(lb)", // domain axis label
"Movement(inch)", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);


Then:

image=chart.createBufferedImage( 300, 200);


The image appeas as:
enter image description here

My save function is:

public static void saveToFile(BufferedImage img)
throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream("D:/Sample.jpg");
JPEGImageEncoder encoder2 =
JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam param2 =
encoder2.getDefaultJPEGEncodeParam(img);
param2.setQuality((float) 200, true);
encoder2.encode(img,param2);
fos.close();
}


I am calling it as:

try{
saveToFile(image);
}catch(Exception e){
e.printStackTrace();
}


The saved image appeas as:

enter image description here

Any suggestion, where I am wrong or how to save it the way it appears or may be I need to save as .png. Can anyone let me know how to save as .png?

Thanks

Answer

A simple Solution:

public static void saveToFile(BufferedImage img)
    throws FileNotFoundException, IOException
    {

        File outputfile = new File("D:\\Sample.png");
    ImageIO.write(img, "png", outputfile);
    }

Saved the image, the way it appears.

Comments