HTML
<img alt="image" th:src="'createFolw?photoId='+${photoId}+'&width=540&height=320'" >
現在瞭解到這能以這種方式來設置圖片大小
controller
@RequestMapping("createFolw")
public void createFolw(HttpServletRequest request, HttpServletResponse response)throws Exception {
Long photoId=RequestUtil.getLong(request,"photoId",0L);
int width = RequestUtil.getInt(request, "width");
int height = RequestUtil.getInt(request, "height");
UpPhoto photoInfo = upPhotoService.getById(photoId);
HttpSession seesion = request.getSession();
byte[] data = photoInfo.getFileStream();
if (width != 0 && height != 0) {
data =upPhotoService.scaleImage(data, width, height);
}
response.setContentType("img/jpg");
response.setCharacterEncoding("utf-8");
try {
OutputStream outputStream = response.getOutputStream();
InputStream in = new ByteArrayInputStream(data);
int len = 0;
byte[] buf = new byte[1024];
while ((len =in.read(buf,0,1024)) != -1) {
outputStream.write(buf,0,len);
}
outputStream.close();
} catch (IOException e){
e.printStackTrace();
}
}
service
/**
* 調整報告圖片大小
* @param data
* @param width
* @param height
* @return
* @throws IOException
*/
@Override
public byte[] scaleImage(byte[] data, int width, int height) throws IOException {
BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));
int imageOldWidth = buffered_oldImage.getWidth();
int imageOldHeight = buffered_oldImage.getHeight();
double scale_x = (double) width / imageOldWidth;
double scale_y = (double) height / imageOldHeight;
double scale_xy = Math.min(scale_x, scale_y);
int imageNewWidth = (int) (imageOldWidth * scale_xy);
int imageNewHeight = (int) (imageOldHeight * scale_xy);
BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);
buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);
buffered_newImage.getGraphics().dispose();
ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
ImageIO.write(buffered_newImage, "jpeg", outPutStream);
return outPutStream.toByteArray();
}