我使用头文件 (LenaArray.h); int lena [511][511] = {162,162,162,etc...}, 导入了 Lena 的二维数组

但现在我想将其转换为灰度图像,我不知道如何请帮助? Image of Lena I'm trying to print

#include <stdio.h>
#include "LenaArray.h"

int main () {

int i,j;

int width = 511;
int height = 511;

for (i = 0; i < height; i ++ )
{
    for(j = 0; j < width; j ++)
    {
        printf("%d",&lena[i][j]);
    }

}


}

最佳答案

#include <stdio.h>

typedef unsigned char U8;
typedef struct { U8 p[4]; } color;


U8 lena[511][511];

void save(char* file_name,int width,int height)
{

    FILE* f = fopen(file_name, "wb");


    color tablo_color[256];
    for (int i = 0; i < 256; i++)
        tablo_color[i] = { (U8)i,(U8)i,(U8)i,(U8)255 };//BGRA 32 bit


    U8 pp[54] = { 'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0 ,
                     40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 32 };
    *(int*)(pp + 2) = 54 + 4 * width * height;  //file size
    *(int*)(pp + 18) = width;
    *(int*)(pp + 22) = height;
    *(int*)(pp + 42) = height * width * 4;      //bitmap size
    fwrite(pp, 1, 54, f);


    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            U8 indis = lena[i][j];
            fwrite(tablo_color+indis,4,1,f);
        }
    }

    fclose(f);

}

int main()
{

    for (int i = 0; i < 511; i++)
    {
        for (int j = 0; j < 511; j++)
        {
            lena[i][j]=i+j;
        }
    }

    save("test.bmp", 511, 511);

}

10-08 00:45