I am trying to use OpenGL to read and render a PPM image by storing its RGB color values in an array. The image that is being displayed is just a blur of colors. I can’t figure out what I am doing wrong.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <iostream>
void my_display()
{
glClear(GL_COLOR_BUFFER_BIT);
int width, height, max_val;
int r, g, b;
int x;
int y;
GLubyte ***image;
char header[70];
FILE * file = fopen("C:\\Users\\Steve\\IMAGE1.ppm", "r");
if (fscanf(file, "%s", &header) != EOF)
{
if (strcmp(header, "P3") == 0)
{
while (!isdigit(header[0]))
{
fscanf(file, "%s", header);
}
fscanf(file, "%d", &width);
fscanf(file, "%d", &height);
fscanf(file, "%d", &max_val);
image = (GLubyte ***)malloc(sizeof(GLubyte **) * width);
for (int i = 0; i <= width; i++)
{
image[i] = (GLubyte **)malloc(sizeof(GLubyte *) * height);
for (int j = 0; j<=height; j++)
{
image[i][j] = (GLubyte *)malloc(sizeof(GLubyte) * 3);
}
}
x = 0;
y = 0;
while (y < height)
{
x = 0;
while (x < width)
{
fscanf(file, "%d", &r);
fscanf(file, "%d", &g);
fscanf(file, "%d", &b);
image[x][y][0] = r;
image[x][y][1] = g;
image[x][y][2] = b;
x++;
}
y++;
}
}
else
{
printf("This is not a valid ppm file");
//exit(1);
}
}
else
{
printf("This file is empty");
//exit(1);
}
fclose(file);
glRasterPos2i(-1.0, -1.0);
glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_INT, image);
glEnd();
glFlush();
}
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitWindowSize(512, 512);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 256.0, 0.0, 256.0);
glMatrixMode(GL_MODELVIEW);
glutCreateWindow(“image”);
glutDisplayFunc(my_display);
glutMainLoop();
}
Can anyone figure it out?