工具包-图像裁剪

 

工具包-图像裁剪


import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageSubUtils {

	private static final Logger log = LoggerFactory.getLogger(ImageSubUtils.class);

	private static BufferedImage imgSub(BufferedImage src, int x, int y, int width, int height) {
		BufferedImage back = src.getSubimage(x, y, width, height);
		return back;
	}

	private static BufferedImage imgSub(BufferedImage src, int width, int height) {

		int srcWidth = src.getWidth(); // 原图宽
		int srcHeight = src.getHeight(); // 原图高

		if (width > srcWidth) {
			width = srcWidth;
		}

		if (height > srcHeight) {
			height = srcHeight;
		}

		BufferedImage back = src.getSubimage(0, 0, width, height);
		return back;
	}

	// 读取图片
	private static BufferedImage file2img(File imgpath) {
		try {
			BufferedImage bufferedImage = ImageIO.read(imgpath);
			return bufferedImage;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 保存图片,extent为格式,"jpg"、"png"等
	private static void img2file(BufferedImage img, String extent, File newfile) {
		try {
			ImageIO.write(img, extent, newfile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 裁剪图片
	 * 
	 * @param src 源文件
	 * @param tar 目标文件
	 * @return
	 */
	public static boolean subImg(File src, File tar, String imageType, int newSize ) {

		if(imageType == null || imageType.length()==0)
		{
			imageType ="jpg";
		}
		
		try {
			BufferedImage bi2 = file2img(src); // 读取图片
			BufferedImage bii2 = imgSub(bi2, newSize, newSize);
			img2file(bii2, imageType, tar); // 生成图片
		} catch (Exception e) {
			log.info("缩略图裁剪失败", e);
			
			return false;
		}

		return true;
	}

	public static void main(String[] args) {

		// 文件与BufferedImage间的转换
		File src = new File("C:\\data\\image\\min.jpg");
		File tar = new File("C:\\data\\image\\min_1.jpg");

		
		boolean r = ImageSubUtils.subImg(src, tar,"png",300);

		System.out.println("success " +r);
		
		String name ="aaa.png";
		String fileExt =name.substring(name.lastIndexOf("."));
		
		System.out.println("fileExt:"+fileExt);

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值