【发布时间】:2022-01-09 22:32:23
【问题描述】:
我的服务器通过上传接收到一个 bmp 字节数组,我读取了它的宽度和高度,但得到了-1。我尝试用下面的代码模拟这个上传案例:
public class ImageReader {
private static URL imgUrl;
public static void main(String[] args) throws IOException {
imgUrl = ImageReader.class.getResource("myimage.jpg");
printWidthHeight(imgUrl, "jpg");
imgUrl = ImageReader.class.getResource("flag.bmp");
printWidthHeight(imgUrl, "bmp");
}
private static void printWidthHeight(URL imgUrl, String format) throws IOException {
BufferedImage image = ImageIO.read(imgUrl);
System.out.println(image.getType());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean isAppropriate = ImageIO.write(image, format, baos);
System.out.println(isAppropriate);
byte[] bytes = baos.toByteArray();
ImageIcon imageIcon = new ImageIcon(bytes);
System.out.format( "%s, %s \n", imageIcon.getIconWidth(), imageIcon.getIconHeight());
}
}
打印出来:
5
true
171, 125
5
true
-1, -1
我找到了
- jpg 仍然有宽度和高度,但 bmp 没有
有人知道原因吗?
【问题讨论】:
-
你能使用带有
Image类型参数的[ImageIcon]constructor吗? -
是的,传递了 bmp 的 BufferedImage 将保持其大小。因为我的目的是模拟上传案例,所以我创建了一个带有字节数组的 ImageIcon。 :)