Can I save the image
I have coded a JSP that will show the image on the browser.
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. Also note that doing this in a JSP file instead of a Java class is not the best practice. It makes the Java code unreuseable by normal Java classes.
精彩评论