读取bmp文件的像素值 [英] read pixel value in bmp file

查看:456
本文介绍了读取bmp文件的像素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能在所有像素[H * W]用C或C ++在Windows 24位读BMP图像的颜色值[更好,没有任何第三方库。我的开发-C ++ 结果
一个工作code将是非常美联社preciated,因为我从来没有在影像阅读和放大器的工作;来到谷歌搜索SO [如果你能谷歌比我好,PLZ提供了一个链接]了。

How can I read the color value of 24bit BMP images at all the pixel [h*w] in C or C++ on Windows [better without any 3rd party library]. I got Dev-C++
A working code will be really appreciated as I've never worked on Image reading & have come to SO after Googling [if you can google better than me, plz provide a link].

推荐答案

您可以试试这个:

unsigned char* readBMP(char* filename)
{
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

    // extract image height and width from header
    int width = *(int*)&info[18];
    int height = *(int*)&info[22];

    int size = 3 * width * height;
    unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);

    for(i = 0; i < size; i += 3)
    {
            unsigned char tmp = data[i];
            data[i] = data[i+2];
            data[i+2] = tmp;
    }

    return data;
}

现在数据应包含(R,G,B)的像素值。像素(i,j)条的颜色存储在数据[J *宽+ I] 数据[J *宽+ I + 1] 数据[J *宽+ I + 2]

Now data should contain the (R, G, B) values of the pixels. The color of pixel (i, j) is stored at data[j * width + i], data[j * width + i + 1] and data[j * width + i + 2].

在最后一部分,每一个第一和第三像素之间的交换完成,因为Windows存储颜色值(B,G,R)的三倍,而不是(R,G,B)。

In the last part, the swap between every first and third pixel is done because windows stores the color values as (B, G, R) triples, not (R, G, B).

这篇关于读取bmp文件的像素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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