我试图将bmp文件中的像素数据复制到c中的文本文件(白色将为0,其他每种颜色都为1),但由于某种原因,文本文件出现了三个区域(三个区域为1)和在错误的方向,我无法弄清楚为什么。无论如何这是我的scipt:
#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#pragma pack(1)
typedef struct {
unsigned char type1; /* Magic identifier */
unsigned char type2;
unsigned int size; /* File size in bytes */
unsigned int reserved;
unsigned long offset; /* Offset to image data, bytes */
} Header;
#pragma pack(2)
typedef struct {
unsigned int size; /* Header size in bytes */
int width,height; /* Width and height of image */
unsigned short int planes; /* Number of colour planes */
unsigned short int bits; /* Bits per pixel */
unsigned int compression; /* Compression type */
unsigned int imagesize; /* Image size in bytes */
unsigned int xresolution,yresolution; /* Pixels per meter */
unsigned int ncolours; /* Number of colours */
unsigned int importantcolours; /* Important colours */
} Infoheader;
typedef struct
{ unsigned char Red, Green, Blue,Reserved;
} Pixel;
void main()
{
int n;
FILE *fin;
Header *fileheader;
Infoheader *information;
Pixel *ppixel,**pImage;
fin=fopen("TEST_web.bmp","rb");
if (fin==NULL)
{
printf("Error reading image\n");
exit(1);
}
int i,j;
fileheader=(Header *)malloc(sizeof(Header));
information=(Infoheader *)malloc(sizeof(Infoheader));
ppixel=(Pixel *)malloc(sizeof(Pixel));
fread(fileheader,sizeof(Header),1,fin);
if ((*fileheader).type1!='B'&&(*fileheader).type2!='M')
{
printf("Not a bmp file\n");
exit(1);
}
n=fread(information, sizeof(Infoheader),1,fin);
if(n!=1)
{
printf("Error reading image information\n");
exit(1);
}
pImage = (Pixel **)malloc(sizeof(Pixel *) * information->height);
for(i = 0; i < information->height; i++)
{ pImage[i] = (Pixel *)malloc(sizeof(Pixel) * information->width);
}
fseek(fin,fileheader->offset,SEEK_SET);
for(i = 0; i < information->width; i++)
{ for(j = 0; j < information->height; j++)
{ fread(&(*ppixel).Red, sizeof(unsigned char), 1, fin);
fread(&(*ppixel).Green, sizeof(unsigned char), 1, fin);
fread(&(*ppixel).Blue, sizeof(unsigned char), 1, fin);
pImage[i][j] = *ppixel;
}
}
char data[information->width][information->height];
for(i = 0; i <information->width; i++)
{ for(j= 0; j<information->height; j++)
{
if((pImage[i][j]).Red==255&&(pImage[i][j]).Green==255&& Image[i][j]).Blue==255)
data[i][j]='0';
else
data[i][j]='1';
}
}
FILE *fout;
fout=fopen("text.txt","wt");
for(i = 0; i < information->width; i++)
{ for(j = 0; j < information->width ; j++)
{ fputc(data[i][j],fout);
}
fputs("\n",fout);
}
free(fileheader);
free(information);
free(ppixel);
for(i = 0; i < information->height; i++)
free(pImage[i]);
fclose(fin);
}
答案 0 :(得分:0)
而不是:
for(i = 0; i < information->width; i++)
{
for(j = 0; j < information->height; j++)
使用类似的东西:
for(y = 0; y < information->height; y++)
{
for(x = 0; x < information->width; x++)
(当然,在扫描位图时也一样。)