我尝试做一个简单的读取.bmp文件,然后输出相同的.bmp文件。现在,它只工作,如果宽度和高度是完全相同的。这是一个很好的指标,我的问题是什么,但我似乎不能弄清楚。我正在寻找任何想法或建议,你们都可能有。还有其他问题,但它们看起来并不完全是我所寻找的。然而,当宽度和高度不同时,我的输出与Read/Write SImple BMP Image C++所示的输出类似-基本上是扭曲的、不完整的和重复的,而不是实际的图像。
下面是我在.bmp文件中读取的代码:
bool LoadBmp(const char *filepath)
{
FILE *f = fopen(filepath, "rb");
if (f)
{
Bwidth = 0;
Bheight = 0;
pixels = NULL;
unsigned char info[54] = {0};
fread(info, sizeof(unsigned char), 54, f);
Bwidth = *(unsigned int *)&info[18];
Bheight = *(unsigned int *)&info[22];
unsigned int size = Bwidth * Bheight * 3; // ((((Bwidth * Bheight) + 31) & ~31) / 8) * Bheight;
pixels = malloc(size);
fread(pixels, sizeof(unsigned char), size, f);
fclose(f);
return true;
}
return false;
}
请注意,我不确定是像下面这样创建大小(Bwidth * Bheight * 3)还是使用注解掉的内容。还请注意,“Bwidth”和“Bheight”被声明为unsigned int,而“pixels”被定义为unsigned char*。此外,我特意不使用结构体来存储.bmp文件数据。
下面是我用来编写刚才加载的.bmp文件的代码:
static bool WriteBMP(int x, int y, unsigned char *bmp, char * name)
{
const unsigned char bmphdr[54] = {66, 77, 255, 255, 255, 255, 0, 0, 0, 0, 54, 4, 0, 0, 40, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 1, 0, 8, 0, 0, 0, 0, 0, 255, 255, 255, 255, 196, 14, 0, 0, 196, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
unsigned char hdr[1078];
int i, j, c, xcorr, diff;
FILE *f;
xcorr = (x+3) >> 2 << 2; // BMPs have to be a multiple of 4 pixels wide.
diff = xcorr - x;
for (i = 0; i < 54; i++) hdr[i] = bmphdr[i];
*((int*)(&hdr[18])) = xcorr;
*((int*)(&hdr[22])) = y;
*((int*)(&hdr[34])) = xcorr*y;
*((int*)(&hdr[2])) = xcorr*y + 1078;
for (i = 0; i < 256; i++) {
j = i*4 + 54;
hdr[j+0] = i; // blue
hdr[j+1] = i; // green
hdr[j+2] = i; // red
hdr[j+3] = 0; // dummy
}
f = fopen(name, "wb");
if (f) {
assert(f != NULL);
c = fwrite(hdr, 1, 1078, f);
assert(c == 1078);
if (diff == 0) {
c = fwrite(bmp, 1, x*y, f);
assert(c == x*y);
} else {
*((int*)(&hdr[0])) = 0; // need up to three zero bytes
for (j = 0; j < y; j++) {
c = fwrite(&bmp[j * x], 1, x, f);
assert(c == x);
c = fwrite(hdr, 1, diff, f);
assert(c == diff);
}
}
fclose(f);
return true;
}
else return false;
}
提前感谢你的帮助。感谢你抽出时间!
3条答案
按热度按时间sauutmhj1#
x9ybnkn62#
jgwigjjp3#