因爲如今應用的複雜性,有的應用經常將上傳的圖片存到數據庫中,可是到顯示時卻要顯示比原圖要小的圖片,可是長款比例還不能變,否則圖片會變形或失真。
java
場景:圖片管理的時顯示一系列小圖片,當點擊是顯示放大的圖片。數據庫
可是如今的圖片有的高度大於寬度,有時寬度大於高度,比例各不相同,因此有時顯示圖片的時候可能不整齊,通常網頁上的方法是用固定的正方形作底色,而後在上面顯示縮小後的圖片,具體的實現代碼以下:app
public File resizeImage(File file, float maxWidth, float maxHeight) { FileOutputStream fos = null; try { // 橫向圖片 Image image = ImageIO.read(file); float w = image.getWidth(null); float h = image.getHeight(null); int previewWidth = 0; int previewHeight = 0; // 等比例縮放 if (log.isDebugEnabled()) { log.debug("w : " + w); log.debug("h : " + h); log.debug("maxWidth : " + maxWidth); log.debug("maxHeight : " + maxHeight); } if (w > h) { // 橫向照片 // 若是照片的橫縱比大於給定寬高的橫縱比,則壓縮使用給定高度 if ((w / h) > (maxWidth / maxHeight)) { previewWidth = Float.valueOf(maxWidth).intValue(); previewHeight = Float.valueOf(h * previewWidth / w).intValue(); } else { previewHeight = Float.valueOf(maxHeight).intValue(); previewWidth = Float.valueOf(w * previewHeight / h).intValue(); } if (log.isDebugEnabled()) { log.debug("w / h > maxWidth / maxHeight : " + ((w / h) > (maxWidth / maxHeight))); log.debug("w / h : " + (w / h)); log.debug("maxWidth / maxHeight : " + (maxWidth / maxHeight)); } } else { // 縱向照片 if (h / w > maxHeight / maxWidth && maxHeight > maxWidth) { previewWidth = Float.valueOf(maxWidth).intValue(); previewHeight = Float.valueOf(h * previewWidth / w).intValue(); } else { previewHeight = Float.valueOf(maxHeight).intValue(); previewWidth = Float.valueOf(w * previewHeight / h).intValue(); } } if (log.isDebugEnabled()) { log.debug("previewWidth : " + previewWidth); log.debug("previewHeight : " + previewHeight); } HttpServletRequest request = ServletActionContext.getRequest(); String tempRoot = request.getSession().getServletContext().getRealPath("文件路徑"); File destFilePath = new File(tempRoot); if (!destFilePath.exists()) { destFilePath.mkdirs(); } File destFile = new File(CommUtils.getString(tempRoot + "/", file.getName())); fos = new FileOutputStream(destFile); BufferedImage bufImage = new BufferedImage(previewWidth, previewHeight, BufferedImage.TYPE_INT_RGB); Graphics g = bufImage.getGraphics(); g.drawImage(image, 0, 0, previewWidth, previewHeight, null); g.dispose(); ImageIO.write(bufImage, CommUtils.getSuffix(file.getName()), fos); return destFile; } catch (Exception e) { log.error("error.", e); } finally { if (fos != null) { try { fos.close(); } catch (Exception e2) { // TODO: handle exception } } } return null; }
CommUtils.javaui
/** * 得到文件後綴 * * @param fileName * @return */ public static String getSuffix(String fileName) { if (null == fileName || "".equals(fileName)) { return ""; } int index = fileName.lastIndexOf("."); if (index > 0) { return fileName.substring(index + 1); } return ""; } /** * 多個對象累加 * * @param objects * @return */ public static String getString(Object... objects) { if (null == objects || objects.length == 0) { return ""; } StringBuilder buf = new StringBuilder(); for (Object object : objects) { buf.append(object); } return buf.toString(); }