读取BMP文件并旋转

时间:2013-03-10 12:39:09

标签: c bitmap

我正在尝试读取BMP文件并将其保存在具有2维的缓冲区中,以便以直角旋转它。但是,最终文件不正确,无法显示。以下代码有什么问题?

#include <fstream.h>
#include <iostream.h>

int main() {
    long int width=686;
    long int height=800 ;
/* open file */
    FILE * bitmap_file= fopen("filename.bmp", "rb");
    if(!bitmap_file) {
        printf("Could not find file.\n");
        fclose(bitmap_file);
        return 0;
    }
    printf("File opened.\n");
    typedef struct buffer1
    {         
        int red;
        int green;
        int blue;
    } buffer1;
    static buffer1 buffer_bitmap1[686][800];
    fseek(bitmap_file, 0, SEEK_SET);
    int count=0;
    for(int i = 0; i <8; ++i){
        for(int j = 0; j <6; ++j){
            fread(&buffer_bitmap1[j][i].red , 1, 1, bitmap_file);    /*for rotate bmp exchange the width with height in matrix.*/
            fread(&buffer_bitmap1[j][i].green, 1, 1, bitmap_file);
            fread(&buffer_bitmap1[j][i].blue, 1, 1, bitmap_file);
            count=count+8;
            fseek(bitmap_file,count, SEEK_CUR);     /*move pointer*/
        }
    }
    fclose(bitmap_file);
    FILE *bitmap_file1= fopen("filename.bmp", "a");
    count=0;
    fseek(bitmap_file, 0, SEEK_SET);
    char * a ="a";
    for(int i = 0; i <6; ++i){
        for(int j = 0; j <8; ++j) {
            fwrite(&buffer_bitmap1[i][j],1,1,bitmap_file1);
            fwrite(&buffer_bitmap1[i][j].blue,1,1,bitmap_file1);
            fwrite(&buffer_bitmap1[i][j].green,1,1,bitmap_file1);
            count=count+8;
            fseek(bitmap_file, 8, SEEK_CUR);     /*move pointer*/
        }
    }
    fclose(bitmap_file);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

至少,您不能简单地从头开始阅读BMP文件,因为它有BMP Header

首先,您需要读取标头int以获取BMP参数(图像大小,数据偏移,每像素位数等)。

第二,为了旋转图像并能够看到结果,你还需要修改标题。