3

I am trying to crop an image loaded thanks to SOIL library, before using it as a texture.

  • So first, how can I load an image, and then convert it to a texture ?
  • And secondly, how to modify (crop, etc..) the image loaded ?

This is what I would like to do:

unsigned char * img = SOIL_load_image("img.png", &w, &h, &ch, SOIL_LOAD_RGBA);
// crop img ...
// cast it into GLuint texture ...
genpfault
  • 51,148
  • 11
  • 85
  • 139
Rafutk
  • 196
  • 1
  • 1
  • 15

1 Answers1

3

You can load a portion of your image by utilizing the glPixelStorei functionality:

// the location and size of the region to crop, in pixels:
int cropx = ..., cropy = ..., cropw = ..., croph = ...;

// tell OpenGL where to start reading the data:
glPixelStorei(GL_UNPACK_SKIP_PIXELS, cropx);
glPixelStorei(GL_UNPACK_SKIP_ROWS, cropy);

// tell OpenGL how many pixels are in a row of the full image:
glPixelStorei(GL_UNPACK_ROW_LENGTH, w);

// load the data to a previously created texture
glTextureSubImage2D(texure, 0, 0, 0, cropw, croph, GL_SRGB8_ALPHA8, GL_UNSIGNED_BYTE, img);

Here's a diagram from the OpenGL spec that might help: subimage diagram

EDIT: If you're using older OpenGL (older than 4.5) then replace the glTextureSubImage2D call with:

glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, cropw, croph, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);

Make sure to create and bind the texture prior to this call (same way you create textures normally).

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • Thanks. I first loaded the image and saved its dimensions. Then, I loaded the same file but as a texture. But when I wanted to crop it with `glTextureSubImage2D`, the function was not defined (OpenGL v 3.0). However `glTexSubImage2D` is callable, but the first parameter is not the texture anymore. I'm beginning with that and the doc got me a bit confused... – Rafutk Oct 18 '19 at 21:18
  • Now it displays the cropped image, but Y inverted. It seems to be normal so I will deal with that. Thanks a lot! – Rafutk Oct 19 '19 at 03:11