Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Opengl tga texture

Posted on 2011-02-15
Medium Priority
Last Modified: 2012-05-11
I am trying to load a tga texture in opengl. I have an example that I am using but the problem I have with it is that it fails to load the file. I have added the tga file in the resource files folder and the code is below. When I say fail to load I mean it outputs it to the screen using this code

cout << "Error opening file" << endl;

not that there is a code error.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <windows.h>	   // Standard header for MS Windows applications
#include <GL/gl.h>		   // Open Graphics Library (OpenGL) header
#include <GL/glut.h>	   // The GL Utility Toolkit (GLUT) Header
#define KEY_ESCAPE 27
#define g_rotation_speed 0.2
float g_rotation;
using namespace std;
class TGA
	bool Load(const char *filename);
	void Release();
	void Draw();
	char *imageData;
	struct tga_header
		unsigned char idLength;
		unsigned char colorMapType;
		unsigned char imageTypeCode;
		unsigned char colorMapSpec[5];
		unsigned short xOrigin;
		unsigned short yOrigin;	
		unsigned short width;
		unsigned short height;
		unsigned char bpp;
		unsigned char imageDesc;
	tga_header tgaheader;
void TGA::Draw()
	glPixelStorei (GL_UNPACK_ROW_LENGTH, this->tgaheader.width);
	if (this->tgaheader.bpp == 32)
		glPixelStorei(GL_UNPACK_ALIGNMENT, 2); 
		glDrawPixels(this->tgaheader.width, this->tgaheader.height, GL_RGBA, GL_UNSIGNED_BYTE, this->imageData);
	if (this->tgaheader.bpp == 24)
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 
		glDrawPixels(this->tgaheader.width, this->tgaheader.height, GL_RGB, GL_UNSIGNED_BYTE, this->imageData);
void TGA::Release()
	free(imageData);		// Free image data from memory
bool TGA::Load(const char* filename)
	fstream filestr; (filename, ios::in | ios::binary);								// Open file
	if (filestr.is_open())														// Do the following actions, if file is opened
		// read TGA header*) &tgaheader , sizeof(struct tga_header));			// Read tga header. For more information: see tga.h and link above
		printf("image type: %i \n", tgaheader.imageTypeCode);	
		// read pixel data
		int imageSize = tgaheader.width * tgaheader.height * tgaheader.bpp;		// Calculate image size
		this->imageData = (char*) malloc(imageSize);							// Reserve space in the memory to store our image data*) this->imageData, imageSize);						// Read image data from file, into the reserved memory place
		 * TGA is stored in BGR (Blue-Green-Red) format,
		 * we need to convert this to Red-Green-Blue (RGB).
		 * The following section does BGR to RGB conversion
		if (tgaheader.bpp == 24)
			for (int i = 0; i < imageSize; i+=3)
				char c = this->imageData[i];
				this->imageData[i] = this->imageData[i+2];
				this->imageData[i+2] = c;
		if (tgaheader.bpp == 32)
			for (int i = 0; i < imageSize; i+=4)
				// 32 bits per pixel   =  4 byte per pixel			
				char c = this->imageData[i];
				this->imageData[i] = this->imageData[i+2];
				this->imageData[i+2] = c;
		cout << "Error opening file" << endl;
		return -1;
	return 0;
 *  Rest of code
typedef struct {
    int width;
	int height;
	char* title;
	float field_of_view_angle;
	float z_near;
	float z_far;
} glutWindow;
glutWindow win;
TGA g_image;
void display() 
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		// Clear Screen and Depth Buffer
	gluLookAt( 4,2,0, 0,0,0, 0,1,0);					    // Define a viewing transformation
	g_image.Draw();											// Draw image to the screen
void initialize () 
    glMatrixMode(GL_PROJECTION);												// select projection matrix
    glViewport(0, 0, win.width, win.height);									// set the viewport
    glMatrixMode(GL_PROJECTION);												// set matrix mode
    glLoadIdentity();															// reset projection matrix
    GLfloat aspect = (GLfloat) win.width / win.height;
	gluPerspective(win.field_of_view_angle, aspect, win.z_near, win.z_far);		// set up a perspective projection matrix
    glMatrixMode(GL_MODELVIEW);													// specify which matrix is the current matrix
    glShadeModel( GL_SMOOTH );
    glClearDepth( 1.0f );														// specify the clear value for the depth buffer
    glEnable( GL_DEPTH_TEST );
    glDepthFunc( GL_LEQUAL );
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );						// specify implementation-specific hints
	GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
    GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
    GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
    glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
    glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
    glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
    glEnable( GL_LIGHT0 );
    glEnable( GL_COLOR_MATERIAL );
    glShadeModel( GL_SMOOTH );
    glDepthFunc( GL_LEQUAL );
    glEnable( GL_DEPTH_TEST );
	glClearColor(0.0, 0.0, 0.0, 1.0);
void keyboard ( unsigned char key, int mousePositionX, int mousePositionY )		
  switch ( key ) 
    case KEY_ESCAPE:        
      exit ( 0 );   
int main(int argc, char **argv) 
	// set window values
	win.width = 640;
	win.height = 480;
	win.title = "OpenGL/GLUT TGA Loader";
	win.field_of_view_angle = 45;
	win.z_near = 1.0f;
	win.z_far = 500.0f;
	g_image.Load("Resource Files/image.tga");
	// initialize and run program
	glutInit(&argc, argv);                                      // GLUT initialization
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );  // Display Mode
	glutInitWindowSize(win.width,win.height);					// set window size
	glutCreateWindow(win.title);								// create Window
	glutDisplayFunc(display);									// register Display Function
	glutIdleFunc( display );									// register Idle Function
    glutKeyboardFunc( keyboard );								// register Keyboard Handler
	glutMainLoop();												// run GLUT mainloop
	return 0;

Open in new window

Question by:tango2009
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
LVL 18

Accepted Solution

Jose Parrot earned 1000 total points
ID: 34901619
Your code is correct.
Please note that the line 211 in the source code must point to a valid TGA file.
Probably you don't have neither a directory "Resource Files" nor a file "image.tga" there.
If you are using Visual C++, put a tga file in the same directory as the source code and change the source code at line 211 properly.


Author Comment

ID: 34905104
I want to use this texture around a teapot that I have drawn, how do I get this texture to apply to the teapot.
LVL 12

Assisted Solution

satsumo earned 1000 total points
ID: 34909965
As JoseParrot says, the problem is the path of the file.  It's a relative path so the program will try to open it relative to the directory where the program runs.  The current directory probably isn't the directory where "Resource Files/image.tga" actually is.

Try specifying the entire path

g_image.Load ("C:/Resource Files/image.tga");

Open in new window

I've assumed you put the 'Resource Files' directory in the root of the C: drive, substitute the actual path.

Alternatively, put the file in the correct folder relative to where the program runs.  If you're using Dev Studio, this defaults to the directory where the source and other project files are stored.  You can change it in the Project Settings, its on the Debug tab, called 'Working Directory' (at least it is in my version of Dev Studio).

Author Comment

ID: 34910754
I have loaded the texture now. I have drawn a teapot using

glutSolidTeapot (0.80);

How do I map this texture to the teapot?
LVL 18

Expert Comment

by:Jose Parrot
ID: 34913320
The image isn't applied as a texture, as per your code. It was simply loaded, as a pure 2D image.
On should enable texture, the same way you have enabled lightning. So, in this particular subject, your code lacks so enablement.

Let me suggest to take a look at the Silicon Graphics' code at
which is applicable to your needs.


Featured Post

Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is about my first experience with programming Arduino.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Introduction to Processes

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question