上傳完成後動態生成縮略圖並儲存。
<%@ page import="java.io.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*" %>
<%
File file = new File("E:\\1110168154_58348.jpg");
String newUrl = "E:\\1110168154_58348_min.jpg";
Image src = ImageIO.read(file);
int oldW = src.getWidth(null), oldH = src.getHeight(null);
float tagSize = 287;
float temp = (oldW > oldH) ? oldW / tagSize : oldH / tagSize;
int newW = Math.round(oldW / temp);
int newH = Math.round(oldH / temp);
BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, newW, newH, null);
FileOutputStream fos = new FileOutputStream(newUrl);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(tag);
fos.close();
%>
按比例縮放,最大邊限制為 287 像素,使用舊版 com.sun.image.codec.jpeg 編碼輸出。