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;
}