用java处理图片的时候,ImageIO读jpg的时候出现exception:bandOffsets.length is wrong。我也遇到过,最终也解决啦,把成果跟大家分享。
原因可能是JPEG图片的ICC信息可能已经被破坏了,所以ImageIO会抛出异常
解决办法:
BufferedImage bis = null;
try{
bis = ImageIO.read(file);
bis.getWidth();
bis.getHeight();
}catch(Exception e){
try
{
ThumbnailConvert tc = new ThumbnailConvert();
tc.setCMYK_COMMAND(file.getPath());
Image image =null;
image = Toolkit.getDefaultToolkit().getImage(file.getPath());
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
image.getWidth(null);
image.getHeight(null);
}catch (Exception e1){
e1.printStackTrace();
}
}
这两句代码,是处理cmyk类型的图片,需要ImageMagick的支持
ThumbnailConvert tc = new ThumbnailConvert();
tc.setCMYK_COMMAND(file.getPath());//用于把cmyk转成rgb
ImageMagick的具体指令是:mogrify -colorspace RGB -quality 100 file1
ThumbnailConvert.java
private String CMYK_COMMAND = "mogrify -colorspace RGB -quality 80 file1";//转换cmyk格式
public void setCMYK_COMMAND(String file1) {
exeCommand(CMYK_COMMAND.replace("file1", file1));
}
public boolean exeCommand(String cmd){
InputStreamReader ir = null;
LineNumberReader input = null;
try
{
//linux下java执行指令:Runtime.getRuntime().exec (String str);
Process process = Runtime.getRuntime().exec (cmd);
ir=new InputStreamReader(process.getInputStream());
input = new LineNumberReader (ir);
while ((input.readLine ()) != null){
}
ir.close();
input.close();
}
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
return false;
}
return true;
}