JAVA實現圖片剪切縮放功能
一般網站都有自定義頭像功能,用戶可以上傳自己喜歡的圖片,然后選取合適的位置,大小,經過裁剪作為自己的頭像。這個過程涉及到js裁剪圖片,服務器處理圖片。
js裁剪一般都使用現成的js類庫,如jcrop,這個比較好用。圖片經過jcrop剪切后,jcrop能夠將剪切信息發送到后臺,其實真正的剪切過程是在后臺做的。jcrop只是搜集數據。
下面是項目中用到的java實現的圖片縮放和剪切功能:
剪切圖片:
/** * 剪切圖片,沒有處理圖片后綴名是否正確,還有gif動態圖片 * @param sourcePath 源路徑(包含圖片) * @param targetPath 目標路徑 null則默認為源路徑 * @param x 起點x坐標 * @param y 起點y左邊 * @param width 剪切寬度 * @param height 剪切高度 * @return 目標路徑 * @throws IOException if sourcePath image doesn't exist */ public static String cutImage(String sourcePath,String targetPath,int x,int y,int width,int height) throws IOException{ File imageFile = new File(sourcePath); if(!imageFile.exists()){ throw new IOException("Not found the images:"+sourcePath); } if(targetPath==null || targetPath.isEmpty()) targetPath = sourcePath; String format = sourcePath.substring(sourcePath.lastIndexOf(".")+1,sourcePath.length()); BufferedImage image = ImageIO.read(imageFile); image = image.getSubimage(x, y, width, height); ImageIO.write(image, format, new File(targetPath)); return targetPath; }
壓縮圖片:
/** * 壓縮圖片 * @param sourcePath 源路徑(包含圖片) * @param targetPath 目標路徑 null則默認為源路徑 * @param width 壓縮后寬度 * @param height 壓縮后高度 * @return 目標路徑 * @throws IOException if sourcePath image does not exist */ public static String zoom(String sourcePath,String targetPath,int width,int height) throws IOException{ File imageFile = new File(sourcePath); if(!imageFile.exists()){ throw new IOException("Not found the images:"+sourcePath); } if(targetPath==null || targetPath.isEmpty()) targetPath = sourcePath; String format = sourcePath.substring(sourcePath.lastIndexOf(".")+1,sourcePath.length()); BufferedImage image = ImageIO.read(imageFile); image = zoom(image,width,height); ImageIO.write(image, format, new File(targetPath)); return targetPath; } /** * 壓縮圖片 * @param sourceImage 待壓縮圖片 * @param width 壓縮圖片高度 * @param heigt 壓縮圖片寬度 */ private static BufferedImage zoom(BufferedImage sourceImage , int width , int height){ BufferedImage zoomImage = new BufferedImage(width, height, sourceImage.getType()); Image image = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); Graphics gc = zoomImage.getGraphics(); gc.setColor(Color.WHITE); gc.drawImage( image , 0, 0, null); return zoomImage; }圖片處理中沒考慮gif動態圖片
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!