我正在尝试编写一个C程序,它采用.raw
灰度图像并逐像素地反转它。
我将每个像素存储在1D char
数组中,然后将每个像素写入输出文件,只是顺序相反。
如果我尝试重现图像,我的程序会工作,但如果我尝试修改数组的索引,我会生成一个不可读的文件。
重现原始
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin, *fout;
char ipath[64], opath[64], *rev, px;
int i, row, read, width, height;
printf("Name of input file: ");
scanf("%s", ipath);
printf("Name of output file: ");
scanf("%s", opath);
printf("Width of image: ");
scanf("%d", &width);
printf("Height of image: ");
scanf("%d", &height);
fin = fopen(ipath, "rb");
fout = fopen(opath, "wb");
rev = (char *)malloc(width * sizeof(char));
row = 0;
while(row < height)
{
for(i = 0; i < width; i++)
{
read = fread(&px, sizeof(char), 1, fin);
rev[i] = px;
}
for(i = 0; i < width; i++)
if(i < width && row < height)
fwrite(&rev[i], sizeof(char), 1, fout);
row++;
}
fclose(fout);
fclose(fin);
return 0;
}
反转图片
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin, *fout;
char ipath[64], opath[64], *rev, px;
int i, row, read, width, height;
printf("Name of input file: ");
scanf("%s", ipath);
printf("Name of output file: ");
scanf("%s", opath);
printf("Width of image: ");
scanf("%d", &width);
printf("Height of image: ");
scanf("%d", &height);
fin = fopen(ipath, "rb");
fout = fopen(opath, "wb");
rev = (char *)malloc(width * sizeof(char));
row = 0;
while(row < height)
{
for(i = 0; i < width; i++)
{
read = fread(&px, sizeof(char), 1, fin);
rev[width - 1 - i] = px;
}
for(i = 0; i < width; i++)
if(i < width && row < height)
fwrite(&rev[i], sizeof(char), 1, fout);
row++;
}
fclose(fout);
fclose(fin);
return 0;
}
出于测试目的,我刚刚使用scanf()
,但我知道它的问题。