java获取jpg图片信息-有损JPG图片处理

        java在进行jpg图片处理时,比如读取本地或者网络图片的长宽、大小等信息,如果jpg图片受损,那么会抛出异常,这时可以先转换成cmyk模式后再进行。

try {
	// 图片处理
	picture = new File("图片url");
	sourceImg = ImageIO.read(new FileInputStream(picture));
	icon.setIconHeight(sourceImg == null ? 0 : sourceImg.getHeight());//获取图片长度
	icon.setIconWidth(sourceImg == null ? 0 : sourceImg.getWidth());//获取图片宽度
} catch (Exception e) {
	logger.error("图片损坏", e);
	try {
		//尝试将jpg转换成CMYK
		this.exeCommand(picture.getPath());
		Image image = null;
		image = Toolkit.getDefaultToolkit().getImage(picture.getPath());
		MediaTracker mediaTracker = new MediaTracker(new Container());
		mediaTracker.addImage(image, 0);
		mediaTracker.waitForID(0);
		icon.setIconHeight(image.getWidth(null) == -1 ? 0 : image.getWidth(null));
		icon.setIconWidth(image.getHeight(null) == -1 ? 0 : image.getHeight(null));
		image.getWidth(null);
		image.getHeight(null);
	} catch (Exception e) {
		logger.error("转换图片异常" + e);
	}
}


//将jpg转换成CMYK
private boolean exeCommand(String path) {
	InputStreamReader ir = null;
	LineNumberReader input = null;
	try {
		Runtime.getRuntime().exec("CLS");
		Process process = Runtime.getRuntime().exec("mogrify -colorspace RGB -quality 80 file1".replace("file1", path));
		ir = new InputStreamReader(process.getInputStream());
		input = new LineNumberReader(ir);
		ir.close();
		input.close();
	} catch (IOException e) {
		logger.error("有损JPG图片格式转换为cmyk模式时发生异常", e);
		return false;
	}

	return true;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值