日期:2014-05-17 浏览次数:20861 次
/** * 对图片进行压缩 * @param srcfile 本地图片路径 * @param imgdist 上传服务器路径 * @param widthdist 压缩宽度 * @param heightdist 压缩高度 */ public void reduceImg(File srcfile, File imgdist, int widthdist,int heightdist) { try { Image src = javax.imageio.ImageIO.read(srcfile); int width = src.getWidth(null); int height = src.getHeight(null); // 宽度除以高度的比例 float wh = (float) width / (float) height; if (1 < wh) { float tmp_heigth = (float) widthdist / wh; BufferedImage tag = new BufferedImage(widthdist,(int) tmp_heigth, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, widthdist,(int) tmp_heigth, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } else { float tmp_width = (float) heightdist * wh; BufferedImage tag = new BufferedImage((int) tmp_width,heightdist, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src, 0, 0, (int) tmp_width,heightdist, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } catch (Exception e) { e.printStackTrace(); } }
------解决方案--------------------