我需要知道如何缩放上传的图像并将其保存在上传文件夹中的服务器上。
我有这个来处理人们可以上传文件的表格。
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);
}
例如,我需要将所有图像重新设置为100x100
答案 0 :(得分:0)
先保存,然后加载,然后缩放,然后重新保存。
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();
}
有关可在getScaledInstance的第三个参数中使用的缩放方法列表,请参阅http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html