gpt4 book ai didi

Java BMP 头文件

转载 作者:行者123 更新时间:2023-11-29 05:48:34 30 4
gpt4 key购买 nike

我尝试从 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 是否正确。

最佳答案

尝试使用 ImageIO

File outImage = new File(name);
ImageIO.write(img, "bmp", outImage);

关于Java BMP 头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885134/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com