1. 程式人生 > >貼一個生成縮圖的類

貼一個生成縮圖的類

實現圖片等比縮放

public class ImageEncoder { public BufferedImage resize(BufferedImage source, int targetW, int targetH) { // 長和寬 int type = source.getType(); BufferedImage target = null; double sx = (double) targetW / source.getWidth(); double sy = (double) targetH / source.getHeight(); // 等比縮放 if (sx > sy) { sx = sy; targetW = (int) (sx * source.getWidth()); } else { sy = sx; targetH = (int) (sy * source.getHeight()); } if (type == BufferedImage.TYPE_CUSTOM) { ColorModel cm = source.getColorModel(); WritableRaster raster = cm.createCompatibleWritableRaster(targetW,targetH); boolean alphaPremultiplied = cm.isAlphaPremultiplied(); target = new BufferedImage(cm, raster, alphaPremultiplied, null); } else{ target = new BufferedImage(targetW, targetH, type); } Graphics2D g = target.createGraphics(); // 開始畫圖 g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY); g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; } public BufferedImage getBufferedImage(String image,int width,int height){ try { BufferedImage srcImage = ImageIO.read(new File(image)); if (width > 0 || height > 0) { srcImage = resize(srcImage, width, height); } return srcImage; } catch (IOException e) { e.printStackTrace(); } return null; } }

Servlet中使用例項:(/ImageProc)

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { synchronized (this) { String img = request.getParameter("img"); int width = Integer.parseInt(request.getParameter("width")); int height = Integer.parseInt(request.getParameter("height")); BufferedImage bi = ie.getBufferedImage(img, width, height); ServletOutputStream sos = response.getOutputStream(); ImageIO.write(bi, "jpg", sos); } } JSP頁面使用<img/>標籤指定src為這個servlet的urlparttern就可以了

<img src="<%=contextPath%>/ImageProc?img=D:/DEMO.jpg&width=160&height=200"/>