PDA

View Full Version : Rendering PPM file - distorted image



ande3674
02-16-2010, 03:12 AM
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", &amp;header) != EOF)
{
if (strcmp(header, "P3") == 0)
{
while (!isdigit(header[0]))
{
fscanf(file, "%s", header);
}

fscanf(file, "%d", &amp;width);
fscanf(file, "%d", &amp;height);
fscanf(file, "%d", &amp;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", &amp;r);
fscanf(file, "%d", &amp;g);
fscanf(file, "%d", &amp;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(&amp;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?

ande3674
02-16-2010, 05:46 AM
If it helps, no matter what PPM file I give it, the image is the exact same. I put in a line to print the RGB values that are being put in the array and they seem to be accurate, (or at least they change depending on the file).

So is the problem is with glDrawPixels?

I also tried adding glPixelStorei(GL_UNPACK_ALIGNMENT,1); in my main method, which didn't help either (although this could be in the wrong place). Any input would be so helpful, I'm stuck.

Thanks again.

Ragnemalm
02-16-2010, 01:42 PM
What happens if you use a texture defined in code as an array? Same thing? Have you tested that you get sensible data in from the PPM reading?

AFAIK glDrawPixels is not the optimal way to draw an image on the screen. I would use a textured polygon.

V-man
02-16-2010, 11:12 PM
Since your array is unsigned bytes, use
glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, image);
instead of
glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_INT, image);