/** * 图片压缩 * @param filePath 原文件路径 * @param w 压缩后宽度 * @param h 压缩后高度 * @return */ public static String imgCompress(String filePath, int w, int h) { try { File file = new File(filePath);// 读入文件 BufferedImage img = ImageIO.read(file); int width = img.getWidth(null); // 得到源图宽 int height = img.getHeight(null); // 得到源图长 if (width / height > w / h) { h = (int) (height * w / width); } else { w = (int) (width * h / height); } // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图 int dot = filePath.indexOf("."); String savePath = filePath.substring(0,dot)+"_"+w+"×"+h+filePath.substring(dot); File destFile = new File(savePath); FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流 //可以正常实现bmp、png、gif转jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); // JPEG编码 out.close(); return savePath; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 按短边 截取正方形的图片 * @param fileName 图片路径 * @throws IOException */ public static String cutImage(String fileName) throws IOException { int dot = fileName.indexOf("."); String savePath = ""; ImageInputStream imageStream = new FileImageInputStream(new File(fileName)); try { FileInputStream fis = new FileInputStream(new File(fileName)); Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream); ImageReader reader = readers.next(); imageStream = ImageIO.createImageInputStream(fis); reader.setInput(imageStream, true); ImageReadParam param = reader.getDefaultReadParam(); int width = reader.getWidth(0); int height = reader.getHeight(0); if(width > height){ width = height; }else{ height = width; } Rectangle rect = new Rectangle(0, 0, width, height); param.setSourceRegion(rect); BufferedImage bi = reader.read(0, param); savePath = fileName.substring(0,dot)+"_"+width+"×"+width+fileName.substring(dot); FileOutputStream fos = new FileOutputStream(new File(savePath)); // 可以正常实现bmp、png、gif转jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos); encoder.encode(bi); // JPEG编码 fos.close(); } finally { imageStream.close(); return savePath; } }