将图像保存为.jpg文件:Java

时间:2013-02-26 17:54:38

标签: java

我将jFreeChart保存到jpeg文件的方式是:

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
); 

然后:

 image=chart.createBufferedImage( 300, 200);

图片显示为: enter image description here

我的保存功能是:

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();
    }

我称之为:

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

保存的图片显示为:

enter image description here

任何建议,我错了或如何以它出现的方式保存它或者我可能需要保存为.png。任何人都可以让我知道如何保存为.png?

由于

3 个答案:

答案 0 :(得分:6)

一个简单的解决方案:

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

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

保存图像,显示方式。

答案 1 :(得分:1)

我宁愿建议您不要使用ImageIo.write来保存图片,最好使用以下功能:

ChartUtilities.saveChartAsJPEG("name of your file", jfreechart, lenght, width);

因为这样你就可以管理图片的大小,但也可以在没有过滤器的情况下保存图片。

答案 2 :(得分:1)

这是一个很好的例子,说明如何做到这一点。

File imageFile = new File("C:\\LineChart.png");
int width = 640;
int height = 480;
try {
    ChartUtilities.saveChartAsPNG(imageFile, chart, width, height);
} catch (IOException ex) {
    System.err.println(ex);
}