JAVA实现图片裁剪

JAVA实现图片裁剪
 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     }
cutImage

 

你可能感兴趣的:(java实现)