Take the 2-minute tour ×

I'm trying to use libpng to split an image into different chunks. The reason being I can't load a texture larger than 512x512 on the hardware I'm working on currently. I accomplished this before with a mixture of SDL and SDL_Image. I basically used the srcrect argument in SDL_BlitSurface to copy just a portion of the image which I then converted into a OpenGL texture. Combine that with a simple loop horizontally then vertically I was able to get an array of textures each a max of 512x512. Then it was just a matter of rendering them at the correct position.

Right now, I don't have the luxury of using SDL, so I figured it's possible to just does this directly myself via libpng. Based on some googling I think its just a matter of using png_read_rows to read just which parts I need. But that's where I'm stuck, I'm not exactly sure how to do that.

Also, if you wonder why I don't just split the images in gimp/photoshop/paint or whatever, it's because I don't control them and am downloading them at runtime.

Thanks for the help in advance.

share|improve this question
add comment

1 Answer

You don't have to mess with extracting the tiles. You can tell OpenGL to just use some portion of the data you give it to initialize the texture. Keyword is glPixelStorei(GL_UNPACK...) parameters. Say your input image has dimensions img.width and img.height and there are 4 bytes to a RGB pixel, i.e. one byte padding for each pixel and your subpicture is defined by subimg.off_x, subimg.off_y, subimg.width, subimg.height. Then you can load it like this:

glPixelStorei(GL_UNPACK_ROW_LENGTH, img.width)
glPixelStorei(GL_UNPACK_SKIP_PIXELS, subimg.off_x)
glPixelStorei(GL_UNPACK_SKIP_ROWS, subimg.off_y)
glTexImage2D(GL_TEXTURE_2D, GL_RGB, 0,
             subimg.width, subimg.height, 0,
             GL_RGBA, GL_UNSIGNED_BYTE, pixeldata)
share|improve this answer
add comment

Your Answer


