我编写了一个将在浏览器上显示图像的JSP。
但我也希望在服务器端保存此图像。
我已经搜索了答案,但我仍然不知道如何保存。
为了保存输出图像,我应该编码什么?
<%@ page import="java.awt.*" %>
<%@ page import="java.awt.image.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="com.sun.image.codec.jpeg.*" %>
<%
Class.forName("org.gjt.mm.mysql.Driver");
java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/clothes","root","clothes");
Statement statement0 = connection.createStatement();
ResultSet rs = statement0.executeQuery("select * from clothes");
int i= 20;
BufferedImage Image = new BufferedImage(600,380, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) Image.getGraphics();
while(rs.next()) {
String Product = rs.getString("clothes_name");
graphics.setColor(Color.white);
graphics.drawString( Product ,15,i);
int Stock = Integer.parseInt(rs.getString("Sales Record"));
if ( Stock >= 25 ) graphics.setColor(Color.green);
if ( Stock >= 15 && Stock < 25 ) graphics.setColor(Color.yellow);
if ( Stock < 15 ) graphics.setColor(Color.red);
graphics.fillRect( 20,i+5, (Stock*10), 10);
i=i+30;
}
rs.close();
connection.close();
response.reset();
ServletOutputStream OutStream = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(OutStream);
encoder.encode(Image);
//I want to save this image, how to do so?
OutStream.close();
%>
答案 0 :(得分:1)
您可以使用大部分相同的代码。你只需要替换
ServletOutputStream OutStream = response.getOutputStream();
通过
OutputStream OutStream = new FileOutputStream("/path/to/file.jpg");
与具体问题无关,请注意Java naming conventions表示变量名称应以小写字母开头。另请注意,在JSP文件而不是Java类中执行此操作是not的最佳做法。它使Java代码不能被普通的Java类重用。