許多開發者在 Java 環境下使用 JFreeChart 繪製統計圖表時,能在 JSP 的 Servlet 中完美呈現;但當嘗試與 PHP 等其他語言整合時,卻常遭遇圖表無法顯示的問題。本文分享一個簡單有效的解決思路,透過「生成圖片 → 儲存至 Web 伺服器 → 以 iframe 嵌入 PHP 頁面」的流程,即可在 PHP 專案中順利展示 JFreeChart 圖表。
<img> 標籤引用該圖片路徑。<iframe>,載入該 JSP 頁面,達到跨語言整合的目的。<%
String startTime = request.getParameter("startTime");
String endTime = request.getParameter("endTime");
String filter = request.getParameter("filter");
Charts charts = new Charts();
String start = startTime == null ? "2013-05-12" : startTime;
String end = endTime == null ? "2013-11-01" : endTime;
String filters = filter == null ? "eventtype" : filter;
JFreeChart chart = charts.getPieChart(startTime, endTime, filter);
String filename = ServletUtilities.saveChartAsJPEG(chart, 800, 400, null, session);
FileOutputStream fos_jpg = null;
File file = new File(application.getRealPath("") + "/charts");
String path = request.getContextPath() + "/charts/NoData.jpg";
try {
file.mkdirs();
fos_jpg = new FileOutputStream(file.getPath() + "/" + filename);
ChartUtilities.writeChartAsJPEG(fos_jpg, 1.0f, chart, 800, 400, null);
} catch (Exception e) {
// 建議記錄錯誤日誌
} finally {
try { if (fos_jpg != null) fos_jpg.close(); } catch (Exception e) {}
}
path = request.getContextPath() + "/charts/" + filename;
%>
<div align="center">
<img src="<%=path %>" name="圖片" width="800" height="400" border="0">
</div>
extjs.chart.chart3D = function(nodeid, id) {
var panel = new Ext.Panel({
border: false,
fitToFrame: true,
html: '<iframe id="frameHelp" src="/getColumnChart.jsp" frameborder="0" width="100%" height="520"></iframe>'
});
return panel;
};
若追求更緊密的整合,可考慮:
<img src="data:image/jpeg;base64,...">。