我认为应该用 fread 替换 for 循环,但是,我不清楚 fread 将如何工作。
fread 如何知道给定位置的绿色像素的值以及将值保存在何处。我的理解是我有一大块堆内存,一个矩形有一个待定的像素数。每个像素有 3 个值。 fread 将如何(或我可以使用的任何其他方法)?
如果有人能解释一下下面的 fread 行如何与我的代码一起工作?这是一项任务,我只是想了解正在发生的事情,因为我们将以此为基础。
fread(pixelD, sizeof(Pixel), width*height, file);
typdef struct
{
unsigned char green;
unsigned char blue;
unsigned char red;
}pixelD;
typedef struct
{
pixelD * pixel;
} Color;
Image * ReadImage(char *filename)
{
int width, height, maxval;
int imgSize = width * height * sizeof(pixel);
//fscanf line was given by prof
fscanf(f_in, "%s\n%d %d\n%d\n", magicNum, &width, &height, &maxval);
pixel = malloc(imgSize);
for(int i = 0; i <imgSize; i++)
{
pixel.green = pixel[i]; ????
pixel.blue = ;
pixel.red = ;
}
}
最佳答案
从表面上看,您正在阅读 PPM file .
阅读标题做这样的事情:
int width, height, max;
my_assert(3==fscanf(f_in, "P6%d%d%d ", &width, &height, &max));
/* TODO: error handling */
格式说明符告诉它读取预期的魔数(Magic Number)(“P6”),然后是整数的第二个、第三个和第四个单词(隐式跳过之间的任何空格),然后消耗一个空格(根据 PPM,“主要是换行符” ) 将文件读取位置设置为二进制数据开始的位置。您可能应该确保 width/height/max 在您的应用程序期望和可以处理的范围内。
然后将剩余的数据读入内存。 fread
从当前读取位置开始读取size*count
字节;无格式:
int channel_width = max < 256 ? 1 : 2; /* PPM channel width can be either 1- or 2-byte */
int rgb = 3;
int imgsize = width*height*rgb*channel_width;
void* texture = malloc(imgsize);
my_assert(imgsize==fread(texture, 1, imgsize, f_in));
/* do something with the texture memory */
此时您可以将纹理指针转换为您喜欢使用的任何结构,例如pixel1D* pixs = texture
(如果 channel 长度为 2 字节请小心,因为您发布的结构不是)。我发现携带元数据和无类型内存块的结构更加灵活,因为主要使用 OpenGL。也许这就是您打算对 Image
类型执行的操作。
代码完全未经测试。祝您调试愉快。
关于c - 了解 fread() 以存储 rgb 像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219937/