我想读取BMP图像的标题,以便当有人写入图像bmp的路径时,它会显示:
我正在研究Java,老师建议使用FileInputStream和FileOutputStream。
代码:
import java.io.FileInputStream;
import java.io.IOException;
public class BMPHeaderReader {
public static void main(String[] args) {
// Replace imagePath's value with the real path of the bmp
String imagePath = "path_to_your_bmp_image.bmp";
readBMPHeader(imagePath);
}
public static void readBMPHeader(String imagePath) {
try (FileInputStream fis = new FileInputStream(imagePath)) {
// Read and skip irrelevant data to reach the relevant header information
fis.skip(18); // Skip to width and height fields
// Read the width (4 bytes, little-endian)
byte[] widthBytes = new byte[4];
fis.read(widthBytes);
int width = byteArrayToInt(widthBytes);
// Read the height (4 bytes, little-endian)
byte[] heightBytes = new byte[4];
fis.read(heightBytes);
int height = byteArrayToInt(heightBytes);
// Print the information
System.out.println("File size: " + fis.available() + " bytes");
System.out.println("Width: " + width + " pixels");
System.out.println("Height: " + height + " pixels");
} catch (IOException e) {
e.printStackTrace();
}
}
public static int byteArrayToInt(byte[] bytes) {
return (bytes[3] & 0xFF) << 24 |
(bytes[2] & 0xFF) << 16 |
(bytes[1] & 0xFF) << 8 |
(bytes[0] & 0xFF);
}
}