1

我是编程新手,所以这可能有一个简单的解决方案。这是我想要做的事情。

我的程序加载一个 .bmp 图像,然后获取宽度和高度来找出图像有多少像素。然后它使用 calloc() 为每个像素的 RGB 值创建三个数组,即 RED、BLUE、GREEN 的数组。我使用了一个 while() 循环来获取第一个像素并将 RGB 值放在它们各自数组的第一个元素中。然后它继续前进,对第二个像素、第三个、第四个像素做同样的事情……这就是我的问题所在,它似乎不想将值放入数组中。我是这样做的,

while(temp=fgetc(fp) != NULL)
{
BLUE[current_pixel]=temp;

temp=fgetc(fp);
GREEN[current_pixel]=temp;

temp=fgetc(fp);
RED[current_pixel]=temp;

current_pixel++;
}

current_pixel 是一个变量,用于跟踪我现在正在查看的像素。

所以我想我真正想知道的是为什么我不能做 BLUE[current_pixel]=temp; 编译时我没有收到任何错误,我使用 printf() 语句检查问题出在哪里。

我已经尝试过 BLUE[1]=temp 并且它工作正常,但这对我的程序没有好处,因为我无法移动到下一个像素来保存值。

预先感谢您的任何帮助!

编辑:我仍然无法让它工作,所以我只想在这里发布整个程序。

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE*fp;
int current_pixel=0;
int temp=0;
int paddingremoved=0;
int cycle=0;
int *RED;
int *BLUE;
int *GREEN;
int imgstrt=0;
int width=0;
int height=0;
int padding=0;

fp=fopen("C:\\Users\\Jason\\Documents\\test.bmp","rb");

if(fp==NULL)
{
printf("Error: File could not be opened");
getchar();
return(0);
}


fseek(fp,10,SEEK_SET);
fread(&imgstrt,1,1,fp);
printf("Image Starts At:%d\n",imgstrt);

fseek(fp,18,SEEK_SET);
fread(&width,4,1,fp);
printf("Image Width:%d\n",width);

fseek(fp,22,SEEK_SET);
fread(&height,4,1,fp);  
printf("Image Height:%d\n",height);

padding=(4 -(width*3)%4)%4;
printf("Padding:%d\n",padding);
getchar();

RED = (int*)calloc(height*width+1,sizeof(int));
GREEN = (int*)calloc(height*width+1,sizeof(int));
BLUE = (int*)calloc(height*width+1,sizeof(int));

if(RED == NULL)
{printf("Red Allocation Faliure\n");}
else{printf("Red Allocation Successful\n");}

if(GREEN == NULL)
{printf(" Green Allocation Faliure\n");}
else{printf("Green Allocation Successful\n");}

if(BLUE == NULL)
{printf("Blue Allocation Faliure\n");}
else{printf("Blue Allocation Successful\n");}

fseek(fp,54,SEEK_SET);
/*---------------------Main Loop--------------------------------*/
while((temp = fgetc(fp)) != EOF)
{
    BLUE[current_pixel]=temp;
    temp=fgetc(fp);
    GREEN[current_pixel]=temp;
    temp=fgetc(fp);
    RED[current_pixel]=temp;
    cycle++;
    current_pixel++;

    printf("[%d,%d,%d::%d] ",RED[current_pixel],GREEN[current_pixel],BLUE[current_pixel],current_pixel);
/*------------------------------------------------------------------*/

    /*---------------------Padding Remover-----------------------*/
    if(cycle==width)
    {printf("\n");
    while (paddingremoved!=padding)
    {fgetc(fp); 
                paddingremoved++;}
    cycle=0;
    paddingremoved=0;}
    /*-----------------------------------------------------------*/
}

getchar();
free(RED);
free(BLUE);
free(GREEN);
return(0);
}
4

2 回答 2

4

由于 C 运算符优先级,您的while条件为:

temp=(fgetc(fp) != NULL)

并不是

(temp=fgetc(fp)) != NULL

使用括号。此外,fgetc返回EOF错误/完成,而不是NULL.

于 2012-12-09T00:54:27.793 回答
1

由于运算符优先级,您的代码始终将每个 BLUE 像素设置为 1。while() 循环条件将结果fgetc(fp)与 NULL 进行比较,然后设置temp为该比较的结果(即 0 或 1)。所以每个蓝色像素都将设置为 1。

试试这个:

while((temp = fgetc(fp)) != EOF)
于 2012-12-09T00:56:34.440 回答