【问题标题】:how to display image in html using jsp call?如何使用jsp调用在html中显示图像?
【发布时间】:2013-09-19 04:38:33
【问题描述】:

我正在尝试在 html 页面中显示图像,调用 <img /> 标记中的 jsp 页面,如下所示。 我创建了动态 web 项目,在 webcontent 文件夹下添加了index.html,在webcontentjsp 文件夹下添加了timeseries.jsp。 当我在服务器上运行项目时,添加 apache tomcat 6.0.18,它是同步的,但是当我输入 url localhost:8080/jfree 时,页面上只显示你好医生和图像图标,但没有图像。

我的 HTML 是,

<!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>

我的 JSP 是,

<%@ 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;
    }
}
%>

但它没有在 jsp 中显示图像?有什么帮助吗?

【问题讨论】:

  • 您真的需要在这里停下来了解一下 JSP 的功能。请注意,提供图像不是 JSP 的任务,而是 Servlet 的任务。
  • 我从这里得到了代码,jspimageupload.blogspot.in/2010/11/…
  • 他们说jsp返回一个图像
  • 嗯,他们是。当您在 JSP 上执行 GET 方法时,您将得到一个 text/html 响应,当您想要/需要一个 image/jpeg(或 png 或任何图像的扩展名)响应时。您不能直接在 JSP 中更改响应类型,但可以在 Servlet 中执行此操作。请注意,由于您将在 GET 中检索图像,因此您必须将所有这些 scriptlet 移动到 doGet 方法内的 Servlet 中。
  • 我也使用了jfreechart,但我没有在服务器上保存图像,而是创建了字节数组并通过响应发送。图像保存的缺点是你需要在工作结束后删除该图像,还有内存空间。

标签: java jsp jfreechart


【解决方案1】:

可能的,而且也很简单。您可以使用以下标记设置 JSP 页面的响应类型:

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

此外,无需将这些图表保存到服务器的文件系统中。可以使用 ImageIO 类将它们直接写入响应的输出流。这是一个示例 JSP 页面,我将其命名为 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());
%>

这里是index.html,它指的是它:

<!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>

结果如下:

【讨论】:

    【解决方案2】:

    首先这个语句不起作用:&lt;img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" /&gt;

    我想你的想法是JSP会返回一个图像,你可以在html&lt;img ...标签中显示图像。嗯,这类似于方法调用,其中某些内容会响应调用者。

    对于您的 HTML,当它加载时,它会尝试使用 /jfree/jsp/Timeseries.jsp 查找文件,假设该文件是 jpeg、bmp 等图像格式文件。它实际上不会执行任何 JSP在服务器上调用。

    因为这个文件是包含一些字节的简单 ascii 文件(即使是有效的 jsp 代码,但不是图像字节);字节实际上并不代表任何图像。所以 HTML 不起作用。

    编辑 1: 无论您想完成什么,都可以这样完成:

    1. 创建一个 servlet,它将在运行时构建映像,然后将其保存在服务器位置。

    2. 测试此应用程序并查看 servlet 是否在服务器位置(例如 /apps/html/images/yourImage.jpg)创建图像文件。

    3. 确保图像位置是 html 可以访问的位置。暂时在同一目录中生成图像 HTML。

    4. 生成图像后,您可以使用图像编辑器打开图像,然后在 HTML。

    5. 编辑 servlet 代码以添加重定向代码,以便 servlet 将您重定向到 html 页面。

    6. 由于在加载 HTML 时,图像已经存在,您的 HTML 应该可以正常工作。

    我希望这些步骤能实现你的目标。

    【讨论】:

    • 如何将这些字节转换为图像?有什么办法吗?
    • 我已经编辑了帖子以叙述可能的解决方案。希望对您有所帮助。
    【解决方案3】:

    如果我正确理解了您的问题,您正在使用 JfreeChart 创建图表图像,并希望在您的 JSP 中显示此图表图像? 最近,我与JFreeChart 库合作,为网站用户创建了许多用于案例研究和分析的图表。 如果这是要求,请尝试以下操作:

    1. 创建图表并保存为 png 到 web-root 文件夹内的任何文件夹 您的网络应用程序。 (如果需要,存储创建的图像的名称 相应地在数据库中)
    2. 在您的 jsp 中使用图像标签并简单地提供您所需的路径 带有图像名称的图像,包括您的上下文路径。

    编辑:您代码中的以下几行将自动将您的图表保存为 png 图像。因此无需担心保存图像。只需给出正确的路径,您必须将图表保存为图像。给我 20 分钟,我会保留整个代码。

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

    编辑 2: 假设在您的应用程序的 web-root 文件夹中,您有一个文件夹名称为“Images” 现在下面的代码将给出我的图像文件夹的路径(包括我的应用程序的上下文路径),如果“chart_folder”在“图像”中不可用,它将创建一个具有此名称的新文件夹:

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

    现在使用下面的代码,我将使用此路径以所需名称保存我的图表图像,并将在请求属性中保留带有图表图像名称的整个路径以在我的 JSP 页面上获取它(您可以根据您的要求进行操作,即使用ServletContext.getContextPath()+"/Images/chart_folder"+&lt;your image name her&gt; 等):

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

    现在在您的 JSP 中,您可以获取带有图像名称的整个路径,以便在标记中使用以显示您的图像。

    如有任何进一步的查询,请随时 ping。

    【讨论】:

    • 是的,您正确地解决了我的问题,先生..但我正在为如何将我的 jfreechart 转换为图像而苦苦挣扎..:(
    • 不需要做任何额外的事情。我正在编辑我的答案并试图指出您的问题。如果您需要任何代码,请询问我。
    • 我需要一个简单的代码来创建一个 xy 绘图仪 jfreechart 然后将其转换为图像,我的代码如上,但它不起作用
    • 我在这里回答了一个类似的问题。看看这个链接:stackoverflow.com/questions/17204745/…如果仍然不能解决您的问题,欢迎您进一步查询。
    • 好的先生,我理解 ChartUtilities.saveChartAsPNG(new File(filePath +"/chart1.png"), chart ,1250, 400);用于实际将图表转换为png,但是这里的文件路径是,是否可以编辑我的代码让你生成png?或者你能引导我到我可以在我的代码中使用 saveChartaspng() 方法的地方吗?
    【解决方案4】:

    可能是下一行发生错误。

    FileInputStream fileInStream = new FileInputStream(image);  
    

    首先使用image.exist()检查图像是否存在。因为它对静态图像工作正常,所以我们将继续前进。

    【讨论】:

      猜你喜欢
      • 2014-05-20
      • 2015-03-13
      • 2013-08-02
      • 1970-01-01
      • 2011-11-08
      • 2012-06-28
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多