user2793926
user2793926

Reputation: 105

how to display image in html using jsp call?

I m trying to display an image in html page calling a jsp page in <img /> tag as follows. I have created dynamic web project, have added index.html under webcontent folder, timeseries.jsp under webcontentjsp folder. When I run the project on server, adding apache tomcat 6.0.18, its synchronised, but when I enter url localhost:8080/jfree it displays only hello doctor and image icon on the page but no image there.

My HTML is,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello doctor
<img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" />
</body>
</html>

My JSP is,

<%@ page import="java.awt.Image" %>
<%@ page import="java.awt.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.awt.BasicStroke"%>
<%@ page import ="org.jfree.ui.ApplicationFrame"%>
<%@ page import="java.io.*" %>
<%@ page import="java.io.File"%>
<%@ page import="org.jfree.chart.*" %>
<%@ page import="org.jfree.chart.axis.*" %>
<%@ page import="org.jfree.chart.entity.*" %>
<%@ page import="org.jfree.chart.labels.*" %>
<%@ page import="org.jfree.chart.plot.*" %>
<%@ page import="org.jfree.chart.renderer.category.*" %>
<%@ page import="org.jfree.chart.urls.*" %>
<%@ page import="org.jfree.data.category.*" %>
<%@ page import="org.jfree.data.general.*" %>
<%@ page import="org.jfree.data.time.Minute"%>
<%@ page import="org.jfree.data.time.Hour"%>
<%@ page import="org.jfree.data.time.TimeSeries"%>
<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>
<%@ page import="org.jfree.data.xy.XYDataset"%>
<%@ page import="org.jfree.chart.plot.XYPlot"%>
<%@ page import="org.jfree.chart.renderer.xy.StandardXYItemRenderer"%>
<%@ page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import=java.sql.Statement" %>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>

<%@ page import="java.awt.image.BufferedImage"%>
<%
try
{
    File image = File.createTempFile("image", "tmp");

    //chart class instance
    Fms fm = new Fms("Graph");

    JFreeChart chart = fm.createChart(fm.dataset);
    ChartUtilities.saveChartAsPNG(image, chart, 500, 400);
    //get input stream
    FileInputStream fileInStream = new FileInputStream(image);
    //output stream foe returning chart as image
    OutputStream outStream = response.getOutputStream(); 
    long fileLength;
    byte[] byteStream;
    fileLength = image.length();
    byteStream = new byte[(int)fileLength];
    //read chart image
    fileInStream.read(byteStream, 0, (int)fileLength);
    //returns chart image whenever called
    response.setContentType("image/png");
    response.setContentLength((int)fileLength);
    response.setHeader("Cache-Control","no-store,no-cache, must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    fileInStream.close();
    outStream.write(byteStream);
    outStream.flush();
    outStream.close();
}
catch (IOException e)
{
    System.err.println("Problem occurred creating chart.");
}
%>
<%!
public class Fms extends ApplicationFrame {
    //Main class
    XYDataset dataset= null;
    public Fms(final String title) {
        super(title);
        dataset= createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(700, 570));
        chartPanel.setMouseZoomable(true, false);
        setContentPane(chartPanel);
    } 
    //chart creation method
    JFreeChart createChart(final XYDataset dataset) {
        final JFreeChart chart = ChartFactory.createTimeSeriesChart(
                                    "Speed Chart",
                                    "Time",
                                    "Speed",
                                    dataset,
                                    true,
                                    true,
                                    false
                                    );
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(false);
        final XYItemRenderer renderer = plot.getRenderer();

        if (renderer instanceof StandardXYItemRenderer) {
            final StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
            rr.setShapesFilled(true);
            renderer.setSeriesStroke(0, new BasicStroke(1.0f));
            renderer.setSeriesStroke(1, new BasicStroke(1.0f));
        }    
        final DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("dd:MM")); 
        try{
            final ChartRenderingInfo info = new ChartRenderingInfo
            (new StandardEntityCollection());
            final File file1 = new File("c:/Documents and Settings/accounts/WebApplication2/web/barchart.png");
            ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
        }catch(Exception e){ }

        return chart;
    }
    //data set generation method
    private XYDataset createDataset() {

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.setDomainIsPointsInTime(true);

        final TimeSeries s1 = new TimeSeries("Series 1", Minute.class);
        s1.add(new Minute(0, 0, 7, 7, 2003), 10.2);
        s1.add(new Minute(30, 12, 7, 8, 2003), 23.0);
        s1.add(new Minute(15, 14, 7, 9, 2003), 48.0);

        final TimeSeries s2 = new TimeSeries("Series 2", Minute.class);
        s2.add(new Minute(0, 0, 7, 7, 2003), 23.0);
        s2.add(new Minute(30, 12, 7, 8, 2003), 9.0);
        s2.add(new Minute(15, 14, 7, 9, 2003), 36.0);

        dataset.addSeries(s1);
        dataset.addSeries(s2);

        return dataset;
    }
}
%>

but its not dispaying the image in jsp? any help?

Upvotes: 0

Views: 7892

Answers (4)

sgbj
sgbj

Reputation: 2274

This is possible, and it's also pretty simple. And you can set the response type of your JSP page with the following tag:

<%@page contentType="image/png" pageEncoding="UTF-8"%>

Furthermore, there's no need to save these charts to the server's file system. They can be written directly to the response's output stream using the ImageIO class. Here's an example JSP page which I've named Chart.jsp:

<%@page import="javax.imageio.*"%>
<%@page import="org.jfree.data.xy.*"%>
<%@page import="org.jfree.chart.*"%>
<%@page import="java.awt.image.*"%>
<%@page contentType="image/png" pageEncoding="UTF-8"%>
<%
    DefaultXYDataset data = new DefaultXYDataset();
    data.addSeries("Set 1", new double[][] {
        {1,  2,  4,  5,  6,  7}, 
        {0, 10, 20, 30, 20, 10}
    });
    JFreeChart chart = ChartFactory.createXYLineChart("Title", "X Label", "Y Label", data);
    BufferedImage bi = chart.createBufferedImage(640, 480);
    ImageIO.write(bi, "png", response.getOutputStream());
%>

And here's index.html which refers to it:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <style>body { text-align: center; }</style>
    </head>
    <body>
        <h1>A Chart:</h1>
        <img src="Chart.jsp" alt="Chart" />
    </body>
</html>

And this is the result:

Chart

Upvotes: 1

Deepak
Deepak

Reputation: 143

May be error is occurring in below line.

FileInputStream fileInStream = new FileInputStream(image);  

First check image exists or not by using image.exist(). Because it is working fine for static image, then we will move forward.

Upvotes: 0

Shailesh Saxena
Shailesh Saxena

Reputation: 3502

If I am understanding your problem correctly, You are creating a chart image using JfreeChart and wanna display this chart image on one of your JSP ? Recently I worked with JFreeChart library to create lots of charts for case study and analysis for a website users. If this is the requirement try below things:

  1. Create chart and save as png to any folder inside web-root folder of your web-application. (If needed store the names of created images in db accordingly)
  2. In your jsp use image tag and simply provide path upto your required image with name of image including your context path.

Edit : Below lines in your code will automatically save your chart into a png image. So no need to worry about saving your images . just give the proper path, where you have to save chart as image. Give me 20 min I will keep entire code.

JFreeChart chart = fm.createChart(fm.dataset);
 ChartUtilities.saveChartAsPNG(image, chart, 500, 400);

Edit 2 : Suppose in your application's web-root folder you have a folder name "Images" Now below piece of code will give the path upto my Images folder(Including context path of my application) and if that "chart_folder" is not available inside "Images" it will create a new one with this name:

 //Get the servers upload directory real path name
                        String filePath = req.getRealPath("/Images");

                        //create the chart_folder folder if do not exists...
                        File folder = new File(filePath);
                        if(!folder.exists())
                         {
                           folder.mkdir();
                         }

Now with below code I will use this path to save my chart image with required name and will keep the entire path with chart image name in request attribute to get it on my JSP page(You can do according to your requirement i.e. use ServletContext.getContextPath()+"/Images/chart_folder"+<your image name her> etc..):

  path=filePath+"/chart_folder";
 ChartUtilities.saveChartAsPNG(new File(path +"/chart3.png"), chart ,no, 400);
                         filePath= path+"\\chart3.png";
                         req.setAttribute("graph_path3",filePath);

Now in your JSP you can get this entire path with image name to use in tag to display your image.

For any further query feel free to ping.

Upvotes: 0

Gyanendra Dwivedi
Gyanendra Dwivedi

Reputation: 5538

First this statement would not work: <img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" />

I guess here your thought process is that the JSP would return an image and you could display the image in html <img ... tag. Well this is not like a method call where something is responded back to the caller.

For your HTML, when it will load, it would try to locate a file with /jfree/jsp/Timeseries.jsp assuming that this file is a image format file like jpeg, bmp etc. It will actually not going to execute any JSP call on the server.

Since this file is simple ascii file containing some bytes(even though a valid jsp code, but not an image bytes); the bytes does not actually represent any image. So HTML is not working.

Edit 1: Whatever you want to accomplish could be done like this:

  1. Create a servlet, which will build the image at runtime, and then save that on a server location.

  2. Test this application and see, if the servlet is creating the image file at a server location say /apps/html/images/yourImage.jpg.

  3. Make sure that the image location is a location where html has access. For the timebeing generate the image in the same directory as of HTML.

  4. Once your image is producing and you could open the image using a image editor, set the same image name(with relative location) in the HTML.

  5. Edit the servlet code to add a redirect code, such that the servlet redirect you to the html page.

  6. Since by the time HTML is loaded, the image is already present, your HTML should work fine.

I hope these step would achieve your goal.

Upvotes: 0

Related Questions