在Java中读取BMP头

问题描述 投票:0回答:1

我想读取BMP图像的标题,以便当有人写入图像bmp的路径时,它会显示:

  • 文件大小(以字节为单位)
  • 宽度(以像素为单位)
  • 高度(以像素为单位)

我正在研究Java,老师建议使用FileInputStream和FileOutputStream。

java image fileinputstream business-process-management
1个回答
0
投票

Java读取BMP图像的头部

这是您的问题的示例代码。

代码:

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.