• Advertisement
Sign in to follow this  

Problems with Loading a PNG

This topic is 4346 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

bool LoadPNG(const char* filename, ImageData* structure)
{
	char header[8];
	int x;
	int y;
	int width;
	int height;
	int number_of_passes;
	long int count3 = 0;
	unsigned char* buffer;
	png_byte color_type;
	png_byte bit_depth;
	png_structp png_ptr;
	png_infop info_ptr;
	
	FILE *fp = fopen(filename, "rb");
	if (!fp)
		return false;
	fread(header, 1, 8, fp);
	if (png_sig_cmp((png_byte*)header, 0, 8))
		return false;
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr)
		return false;
	info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
		return false;
	if (setjmp(png_jmpbuf(png_ptr)))
		return false;
	png_init_io(png_ptr, fp);
	png_set_sig_bytes(png_ptr, 8);
	png_read_info(png_ptr, info_ptr);
	structure->w = info_ptr->width;
	structure->h = info_ptr->height;
	width = info_ptr->width;
	height = info_ptr->height;
	number_of_passes = png_set_interlace_handling(png_ptr);
	png_read_update_info(png_ptr, info_ptr);
	
	if (setjmp(png_jmpbuf(png_ptr)))
		return false;

	png_bytep* row_pointers = new png_bytep[height];
	for (int y=0; y<height; y++)
		row_pointers[y] = new png_byte[info_ptr->rowbytes];
	png_read_image(png_ptr, row_pointers);

	buffer = new unsigned char[4*width*height];
	
	for (int count = 0; count < height; count++){
		for (int count2 = 0; count2 < width*4; count2++){
			buffer[count3] = row_pointers[count][count2];
			count3++;
		}
                Code Was Added Here
		delete[] row_pointers[count];
	}
	delete[] row_pointers;
	GenerateTexture(buffer,structure);
	delete[] buffer;
    fclose(fp);
    return true;
}
There's my LoadPNG function. It just suddenly stopped working on one of the two images I'm trying to load, a 1024x1024 starfield. So I added in the following code just before the end, into the spot indicated:
if (count > 1022){
		char temp[5];
		char line[60];
		itoa(count3,temp,10);
		strcpy(line,"Pixels Counted: ");
		strcat(line,temp);
		itoa(count,temp,10);
		strcat(line,"\nHeight: ");
		strcat(line,temp);
		MessageBox(NULL,line,APP_NAME,MB_OK);
		}
And now it works. Why would this help it?

Share this post


Link to post
Share on other sites
Advertisement
FYI, I can see at least 7 locations where that function can return without closing the file or releasing a bunch of data.

I'm pretty sure you can use png_get_rows() and not need to worry about allocating and releasing all those rows, too.

I'm not sure why that makes it work, I imagine you've managed to clobber something important.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement