BMP 颜色反转功能不起作用 [英] Function for BMP color inverting doesn't work

查看:16
本文介绍了BMP 颜色反转功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些快速代码,用于反转 BMP 图像的颜色.我使用由油漆创建的 40x40 维 BMP 图像进行测试.然而,该函数似乎用白色像素完全填充它.

I wrote some quick code that is supposed to invert colors of a BMP image. I test with a 40x40 dimensional BMP image, created by paint. However the function seem to fill it entirelly with white pixels instead.

void
negate
(char *FILE_NAME)
{
    FILE* fp = fopen(FILE_NAME, "r+b");
    uint_64 raw_data, i;

    fseek(fp, 35, SEEK_SET);
    //raw_data = fgetc(fp) + fgetc(fp)*256;
    raw_data = 4800; // calculated

    fseek(fp, 54, SEEK_SET);
    for(i = 54; i != 54 + raw_data; i++) // <=
    {
        int old = fgetc(fp);
        fseek(fp, i, SEEK_SET);
        fputc(255 - old, fp);
    }

    fclose(fp);
}

我哪里弄错了?

推荐答案

在循环中添加 fseek 修复了它,虽然我不明白为什么:

Adding an fseek into the loop fixes it, although I don't understand why:

for (i = 54; i != 54 + raw_data; i++) // <=
{
    fseek(fp, i, SEEK_SET);
    int old = fgetc(fp);

    fseek(fp, i, SEEK_SET);
    fputc(255 - old, fp);
}

为了找出问题,我这样做是为了查看流中的位置是否正确:

In trying to figure out the problem, I did this, to see if the position in the stream was correct:

for (i = 54; i != 54 + raw_data; i++) // <=
{
    long x = ftell(fp);
    printf("%d,", x);

    int old = fgetc(fp);

    fseek(fp, i, SEEK_SET);
    fputc(255 - old, fp);
}

确实如此.它输出 54,55,56,57,... 所以 fseek() 不是必需的!但是,如果您查看 fgetc() 的结果,旧"值似乎总是在 54 处读取像素.我认为 @RSahu 是正确的:不要像那样读写一个文件.最好将数据读入缓冲区,然后取反缓冲区,然后将其写入磁盘.或者完全写入不同的文件.

And indeed it is. It ouputs 54,55,56,57,... so the fseek() should not be necessary! But if you look at the result of the fgetc(), the "old" value always seems to be reading the pixel at 54. I think @RSahu was correct: don't read and write like that to one file. Better to read the data into a buffer, then negate the buffer, then write it to disk. Or write to a different file entirely.

也许这与缓冲有关?

这篇关于BMP 颜色反转功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆