1

我尝试从 BufferedImage 制作 BMP 文件。这是我尝试在 bmp 文件中写入标题和像素的功能。

我有一个错误,但我找不到。我需要你的帮助。

static void writeToBMP(BufferedImage img, String name)
{
    //File header
    int bfType = 0x424d;
    int bfSize = (img.getHeight()*img.getWidth()*3)+54; // File size
    short bfReserved1 = 0; // Reserved
    short bfReserved2 = 0;
    int bfOfBytes = 54; // Header size

    //Header info
    int biSize = 40; // Header 2 size
    int biWidth = img.getWidth(); // Width in pixels
    int biHeight = img.getHeight(); // Height in pixels
    short biPlanes = 1; // Nr of planes
    short biBitCount = 24; // Nr bites per pixel
    int biCompression = 0;
    int biSizeImage = (img.getHeight()*img.getWidth()*3); // Image size
    int biXPelsPerMeter = 0;
    int biYPelsPerMeter = 0;
    int biClrUsed = 0;
    int biClrImportant = 0;

    File file = new File(name);

    try {
        OutputStream stream = new FileOutputStream(file);
        fOut = new DataOutputStream(stream);
        fOut.writeShort(bfType);
        fOut.writeInt(bfSize);
        fOut.writeShort(bfReserved1);
        fOut.writeShort(bfReserved2);
        fOut.writeInt(bfOfBytes);

        //Write Header Info
        fOut.writeInt(biSize);
        fOut.writeInt(biWidth);
        fOut.writeInt(biHeight);
        fOut.writeShort(biPlanes);
        fOut.writeShort(biBitCount);
        fOut.writeInt(biCompression);
        fOut.writeInt(biSizeImage);
        fOut.writeInt(biXPelsPerMeter);
        fOut.writeInt(biYPelsPerMeter);
        fOut.writeInt(biClrUsed);
        fOut.writeInt(biClrImportant);
        for(int x=0; x<img.getWidth(); x++)
        {
            for(int y=0; y<img.getHeight(); y++)
            {
                Color c = new Color(img.getRGB(x,y));
                fOut.writeByte(c.getRed());
                fOut.writeByte(c.getBlue());
                fOut.writeByte(c.getGreen());
            }
        }
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我试图只写标题,标题大小 = 54 字节。

我不知道我计算的 bfSize 和 biSizeImage 是否正确。

4

2 回答 2

2

尝试使用 ImageIO

File outImage = new File(name);
ImageIO.write(img, "bmp", outImage);
于 2013-02-14T22:24:13.453 回答
1

要解决我的问题,我需要使用 LITTLE_ENDIAN 字节顺序。为此,我使用:

    ByteBuffer buffer = ByteBuffer.allocate(54);
    buffer.putInt(bfSize);
    buffer.putShort(bfReserved1);
    buffer.putShort(bfReserved2);
    buffer.putInt(bfOfBytes);
    buffer.putInt(biSize);
    buffer.putInt(biWidth);
    buffer.putInt(biHeight);
    buffer.putShort(biPlanes);
    buffer.putShort(biBitCount);
    buffer.putInt(biSizeImage);
    buffer.putInt(biXPelsPerMeter);
    buffer.putInt(biYPelsPerMeter);

    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.flip();
于 2013-02-15T18:43:38.923 回答