JAVA實現圖片裁剪

來源:互聯網
上載者:User

標籤:

 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 IOException12      */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\n18             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     }
cutImage

 

JAVA實現圖片裁剪

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.