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动态图片,那个需要特殊处理...


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值