[英]why read a byte array of bmp and the width and height lost
我的服務器通過上傳接收到 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
我發現
有誰知道原因?
來自 Java 文檔,ImageIcon 不支持 BMP 格式:
感謝您的提示。 我發現如果我用ImageIO
讀取這些字節,我可以成功獲得圖像的寬度和高度。
public class ImageReader {
private static URL imgUrl;
private static byte[] bytes;
public static void main(String[] args) throws IOException {
imgUrl = ImageReader.class.getResource("myimage.jpg");
bytes = getBytes(imgUrl, "jpg");
printWidthHeight(bytes);
imgUrl = ImageReader.class.getResource("flag.bmp");
bytes = getBytes(imgUrl, "bmp");
printWidthHeight(bytes);
}
private static void printWidthHeight(byte[] bytes) throws IOException {
ImageIcon imageIcon = new ImageIcon(bytes);
System.out.format( "%s, %s \n", imageIcon.getIconWidth(), imageIcon.getIconHeight());
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
ImageIcon imageIcon2 = new ImageIcon(image);
System.out.format( "%s, %s \n", imageIcon2.getIconWidth(), imageIcon2.getIconHeight());
}
private static byte[] getBytes(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();
return bytes;
}
}
5
true
171, 125
171, 125
5
true
-1, -1
124, 124
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.