1 /** 2 * 裁剪圖片 3 * @param src 源圖片 4 * @param dest 裁剪後的圖片 5 * @param x 裁剪範圍的X座標 6 * @param y 裁剪範圍的Y座標 7 * @param w 裁剪範圍的高度 8 * @param h 裁剪範圍的寬度 9 * @param destW 裁剪後圖片的寬度 10 * @param destH 裁剪後圖片的高度 11 * @throws IOException 12 */ 13 public static void cutImage(String src, String dest, int x, int y, int w, 14 int h,int destW,int destH) throws IOException { 15 try{ 16 17 //未知問題,不知道為啥路徑的最後會有\r\n 18 19 src = src.replace("\r\n", ""); 20 dest = dest.replace("\r\n", ""); 21 System.out.println("CutImage:src=" + src + ";dest=" + dest + ";x=" + x + ";y=" + y); 22 File file = new File(src); 23 if(file.exists()){ 24 Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg"); 25 ImageReader reader = (ImageReader) iterator.next(); 26 InputStream in = new FileInputStream(src); 27 ImageInputStream iis = ImageIO.createImageInputStream(in); 28 reader.setInput(iis, true); 29 ImageReadParam param = reader.getDefaultReadParam(); 30 Rectangle rect = new Rectangle(x, y, w, h); 31 param.setSourceRegion(rect); 32 BufferedImage bi = reader.read(0, param); 33 if(w != destW){ //被拉伸或者縮小過 34 bi.flush(); 35 BufferedImage newImage = new BufferedImage(destW,destH,bi.getType()); 36 Graphics g = newImage.getGraphics(); 37 g.drawImage(bi,0,0,destW,destH,null,null); 38 g.dispose(); 39 ImageIO.write(newImage, "jpg", new File(dest)); 40 }else{ 41 ImageIO.write(bi, "jpg", new File(dest)); 42 } 43 iis.close(); 44 in.close(); 45 //最後刪除臨時檔案 46 file.delete(); 47 }else{ 48 System.out.println("找不到要裁剪的檔案:FileName=" + src); 49 } 50 }catch(Exception ex){ 51 ex.printStackTrace(); 52 } 53 }