[英]Scale image after upload JSP
I need to know how i can scale the uploaded images and save it on the server in the Upload folder. 我需要知道如何缩放上载的图像并将其保存在服务器上的“上载”文件夹中。
I have this to process the the form where people can upload there files. 我用这个来处理人们可以在那里上传文件的表格。
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
} catch (java.io.IOException ioe) {
resp = ioe.getMessage();
}
request.setAttribute("message", resp);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
For example i need to rezise all the image to 100x100 例如我需要将所有图像缩放到100x100
First save it, then load it, then scale, then resave it. 首先保存它,然后加载它,然后缩放,然后重新保存它。
try
{
BufferedImage img = ImageIO.read(new File(in_path));
Image scaled = img.getScaledInstance(100, 100, Image.SCALE_FAST);
ImageIO.write(scaled, "png", out_path);
}
catch (Exception ex)
{
System.out.println(ex.getMessage();
}
See http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html for list of scaling methods that can be used in the third parameter of getScaledInstance 有关可在getScaledInstance的第三个参数中使用的缩放方法列表,请参见http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.