从C中的2D数组读取镜像

时间:2016-04-13 04:39:20

标签: c arrays image file 2d

我正在用C编写程序,其中我正在读取带有2D数组的bmp图像。我应该将原始图像+相反的正确作为输出。

我在这里的代码应该是这样做的,但图像打印在彼此的顶部上。如果有人知道如何解决这个问题,我感谢你的帮助。

int main(void) {

    // Opens file to read the image from
    FILE * infile = fopen("inputImage.bmp", "rb");

    // Creates file to write the image to after modifications     
    FILE * outfile = fopen("flip.bmp", "wb");

    //Bmp images have headers the next 3 lines of code store the header of the input image
    unsigned char headersPart1[2];
    int filesize;    
    unsigned char headersPart2[48];

    // This space[] [] creates the array to which to write the input image AND its inverse right next to each other  the image file is 160 * 240
    // The 3 is for the rgb values.. since its a 2D array we want to use every single //part of the image to work with    
    unsigned char space[160][3*240]; 

    //The array to which to copy the results to (original image + INVERSE) 
    unsigned char mirror[160][3*480]; 

    fread(headersPart1,sizeof(char) ,2,infile);
    fread(&filesize,sizeof(char) ,4,infile);
    fread(headersPart2,sizeof(char) ,48,infile);  
    fread(space,sizeof(char) ,filesize-54,infile);  

    // copying what in the original image array (space[][]) into the new //array mirror[][]
    for ( int row = 0; row < 240*3 ; row++ ) {
        for (int col = 0 ; col < 160; col++) {

            char temp = space[col][row];
            mirror[col][row] = space[col][row];

            //Starts printing the inverse of the original image, starting at the index where the original image will end
            mirror[col][720+row]=  space[col][719-row];

            space[col][row] = temp;

        }
    }

    // Puts everything back into the outfile , once i save and run on GCC this gives me an image and its inverse on top of each other
    fwrite(headersPart1,sizeof(char) ,2,outfile);
    fwrite(&filesize,sizeof(char) ,4,outfile);
    fwrite(headersPart2,sizeof(char) ,48,outfile);

    //sends whats in mirror [][] to the outfile
    //54 is the size of the header (bmp images))
    fwrite(mirror,sizeof(char) ,filesize-54,outfile);    

    return 0;
}

PS:我在GCC上运行这个

1 个答案:

答案 0 :(得分:0)

The BMP file format you can find here

关于支持不同版本的BMP,检查分辨率,颜色深度,调色板预置等,您的加载程序不完整。

但是对于你想要使用它的东西,你可能有一个固定的输入,总是相同的分辨率等。

但是你希望得到的图像宽两倍。因此,标题中的一些细节必须改变:

&#34;文件大小&#34;
&#34;位图宽度,以像素为单位(有符号整数)&#34;