public static void saveImageAsJpg(String inFilePath, String outFilePath, int width, int hight, boolean proportion)throws Exception { File file = new File(inFilePath); InputStream in = new FileInputStream(file); File saveFile = new File(outFilePath);
BufferedImage srcImage = ImageIO.read(in); if (width > 0 || hight > 0) { // 原图的大小 int sw = srcImage.getWidth(); int sh = srcImage.getHeight(); // 如果原图像的大小小于要缩放的图像大小,直接将要缩放的图像复制过去 if (sw > width && sh > hight) { srcImage = resize(srcImage, width, hight); } else { String fileName = saveFile.getName(); String formatName = fileName.substring(fileName .lastIndexOf('.') + 1); ImageIO.write(srcImage, formatName, saveFile); return; } } // 缩放后的图像的宽和高 int w = srcImage.getWidth(); int h = srcImage.getHeight(); // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取 if (w == width) { // 计算X轴坐标 int x = 0; int y = h / 2 - hight / 2; saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取 else if (h == hight) { // 计算X轴坐标 int x = w / 2 - width / 2; int y = 0; saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile); } in.close(); } /** * 实现缩放后的截图 * @param image 缩放后的图像 * @param subImageBounds 要截取的子图的范围 * @param subImageFile 要保存的文件 * @throws IOException */ private static void saveSubImage(BufferedImage image, Rectangle subImageBounds, File subImageFile) throws IOException { if (subImageBounds.x < 0 || subImageBounds.y < 0 || subImageBounds.width - subImageBounds.x > image.getWidth() || subImageBounds.height - subImageBounds.y > image.getHeight()) { System.out.println("Bad subimage bounds"); return; } BufferedImage subImage = image.getSubimage(subImageBounds.x,subImageBounds.y, subImageBounds.width, subImageBounds.height); String fileName = subImageFile.getName(); String formatName = fileName.substring(fileName.lastIndexOf('.') + 1); ImageIO.write(subImage, formatName, subImageFile); }