我想检查传递的文件是否是图像,如果不是,我想显示一条消息,指示该文件不是图像.
try{
Image img = ImageIO.read(new File(name));
}catch(IOException ex)
{
valid=false;
System.out.println("The file" + name + "could not be opened, it is not an image");
}
Run Code Online (Sandbox Code Playgroud)
当文件(引用name)不是图像有效时未设置为false,为什么会发生这种情况?我应该更改例外的类型吗?我已经阅读了关于try-catch的内容,据我所知,如果ImageIO.read失败并且异常的类型是IOException,将执行catch块的内容.那为什么不执行呢?
有没有其他方法来检查文件是否是图像?
从db获取图像后,当我尝试调整大小时,使用下面的代码传递宽度
public static BufferedImage resize(final byte[] pImageData,
final int width, final int height, final int maxLength, final int minLength, final String imageSubType) throws Exception {
InputStream is = null;
BufferedImage resizeImageJpg = null;
try {
is = new ByteArrayInputStream(pImageData);
BufferedImage originalImage = ImageIO.read(is);
--------------------
}
}
Run Code Online (Sandbox Code Playgroud)
行抛出以下异常:
BufferedImage originalImage = ImageIO.read(is);
Run Code Online (Sandbox Code Playgroud)
例外:
Caused by: java.awt.color.CMMException: Invalid image format
at sun.awt.color.CMM.checkStatus(CMM.java:131)
at sun.awt.color.ICC_Transform.<init>(ICC_Transform.java:89)
at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:516)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1169)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1137)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:948)
at javax.imageio.ImageIO.read(ImageIO.java:1422)
at javax.imageio.ImageIO.read(ImageIO.java:1326)
Run Code Online (Sandbox Code Playgroud)
有关为何仅针对某些图像抛出此错误的任何想法.图像有什么问题吗?如果是这样,那可能是什么错误