我正在尝试读取PNG图像的尺寸,但在执行此操作时遇到以下错误 -
Exception in thread "main" javax.imageio.IIOException: I/O error reading PNG header!
at com.sun.imageio.plugins.png.PNGImageReader.readHeader(PNGImageReader.java:307)
at com.sun.imageio.plugins.png.PNGImageReader.readMetadata(PNGImageReader.java:637)
at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1212)
at com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1560)
at javax.imageio.ImageIO.read(ImageIO.java:1422)
at javax.imageio.ImageIO.read(ImageIO.java:1326)
以下是我所拥有的代码 -
InputStream is = new ByteArrayInputStream(myImgByteArray);
BufferedImage image = ImageIO.read(is);
System.out.println("Height: " +image.getHeight()+ "Width: " +image.getWidth());
有人可以建议我需要做些什么来解决这个问题吗?
答案 0 :(得分:0)
您可以使用另一种方式获取图像尺寸:
BufferedImage image = javax.imageio.ImageIO.read(new File(imageFilePath));
System.out.println(image.getHeight());
System.out.println(image.getWidth());
答案 1 :(得分:0)
这取决于你如何构建myImgByteArray
。试试这个。
BufferedImage image = ImageIO.read(new FileInputStream((new File("resources/1.png"))));
System.out.println("Height: " + image.getHeight() + "Width: " + image.getWidth());
你可以尝试任何一个
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
答案 2 :(得分:0)
当您在BuggeredImage中加载图像时,可能会出现问题。他是我的测试代码。
BufferedImage image = null;
try {
image = ImageIO.read(new File("/home/adrian/Documents/wave.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Height: " +image.getHeight()+ " Width: " +image.getWidth());
这是输出:
Height: 1170 Width: 2576
BUILD SUCCESSFUL (total time: 0 seconds)
告诉我们你如何获得myImgByteArray,以便我们可以看到之前是否有错误。
答案 3 :(得分:0)
你可以尝试这样:
public LoadImageApp() {
try {
img = ImageIO.read(new File("/workspace/ImageProject/src/myPic.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100,100);
} else {
System.out.println("Height: " +img.getHeight()+ " Width: " +img.getWidth());
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
确保正确调用文件位置!在Linux中,您的路径必须采用以下格式:
/path/to/my/file.png
在Windows中,这是文件的路径:
C:\\workspace\\path\to\myFile.png