Generating GIF/JPEG/PNG images

A chart can be encoded into a GIF,JPEG or PNG binary stream and outputted to a file. Another use is to generate a encoded binary stream upon a request submitted to a servlet for delivering a chart image. JetChart is then invoked to create the requested chart image, encoding it into the desired format. After that, the servlet delivers the binary stream back to the requester using a ServletOutputStream object.

Chart encoding into one of the image formats available is provided by the ChartEncoder class. The application below plots two stacked bar series. After clicking the button located in the top panel, the chart is encoded into a JPEG stream and is outputted to a file.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.jinsight.jetchart.*;
import java.io.*;

public class Main extends JFrame implements ActionListener  {

    Graph graph;
    
    ChartEncoder chartEncoder;

    JButton button;
    
    public Main() { 
	
	JPanel topPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
	button=new JButton("Generate JPEG file");
	button.addActionListener(this);
	
	topPanel.add(button);
	
	graph=new Graph(new String[]{"l1","l2","l3","l4","l5"});
	graph.setTitle(new String[]{"The JetChart Library","Generating GIF/JPEG/PNG images"});
	graph.set3DEnabled(true);
	graph.setHorizontalGraphEnabled(true);
		
	chartEncoder=new ChartEncoder(graph);
	
	StackBarSerie sb1=new StackBarSerie(new double[]{100,70,80,90,50},"Stacked bar series 1");
	sb1.setColor(Color.yellow);
	
	StackBarSerie sb2=new StackBarSerie(new double[]{-40,-60,70,-80,90},"Stacked bar series 2");
	sb2.setColor(Color.orange);
	
	graph.addSerie(sb1);
	graph.addSerie(sb2);
	
	graph.getGraphSet(0).getGrid().setEnabled(true);
	
	Container ct=getContentPane();
	
	ct.add(graph);
	ct.add("North",topPanel);
	
	setSize(500,400);
	
	setVisible(true);
	
    }
    
    public void actionPerformed(ActionEvent evt) {
           
	FileOutputStream out=null;
	try {
	    File f=new File("output.jpg");
	    out=new FileOutputStream(f);
	    
	    // Encodes chart image into a jpeg file, setting quality to 85%.
	    chartEncoder.jpegEncode(out,85);
	    
	    // To encode chart into a GIF or PNG format, disable the line above and
	    // enable one of the following lines. Change the file extension accordingly.
	    //chartEncoder.gifEncode(out);
	    //chartEncoder.pngEncode(out,9);
	    
	}   
	catch (IOException e) {
	    e.printStackTrace();
	}
	finally {
	    try {
		if (out!=null)
		    out.close();
	    }
	    catch (IOException e) {
	    }
	}
	
    }
    
    public static void main(String[] args) {
	new Main();
    }
    
}