[英]Can I save the image
I have coded a JSP that will show the image on the browser. 我已经编写了一个JSP,它将在浏览器上显示图像。
But I also want to save this image in the server-side. 但我也想将此图像保存在服务器端。
I have searched the answer but I still don't know how to save. 我已经搜索了答案,但是我仍然不知道如何保存。
What should I code in order to save output image? 为了保存输出图像,我应该编写什么代码?
<%@ 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();
%>
You can use much of the same code. 您可以使用许多相同的代码。 You just need to replace
您只需要更换
ServletOutputStream OutStream = response.getOutputStream();
by 通过
OutputStream OutStream = new FileOutputStream("/path/to/file.jpg");
Unrelated to the concrete problem, please note that Java naming conventions state that variable names ought to start with lowercase. 与具体问题无关,请注意, Java命名约定规定变量名称应以小写字母开头。 Also note that doing this in a JSP file instead of a Java class is not the best practice.
还要注意的是,在一个JSP文件,而不是一个Java类这样做是不是最好的做法。 It makes the Java code unreuseable by normal Java classes.
它使普通Java类无法重用Java代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.