Reputation: 631
I'm using C and stb_image, and image data is stored in an unsigned char*
where a group of 4 elements represents a pixel, with r, g, b, and a channels respectively. I'm trying to get pixels of part of an image, for a sort of spritesheet loader. Currently I have this:
static void getGlyphTexture(unsigned char *dataOut, unsigned char *dataIn, size_t bitmapWidth, size_t glyphSize, size_t index) {
for (size_t y = 0; y < glyphSize; y++) {
for (size_t x = 0; x < glyphSize; x++) {
dataOut[4 * (glyphSize * x + y) + 0] = dataIn[4 * (bitmapWidth * x + y) + 0];
dataOut[4 * (glyphSize * x + y) + 1] = dataIn[4 * (bitmapWidth * x + y) + 1];
dataOut[4 * (glyphSize * x + y) + 2] = dataIn[4 * (bitmapWidth * x + y) + 2];
dataOut[4 * (glyphSize * x + y) + 3] = dataIn[4 * (bitmapWidth * x + y) + 3];
}
}
}
The above code takes in an image dataIn
and outputs part of the image into dataOut
. It works fine right now, copying the very first segment of the image, of glyphSize * glyphSize
dimensions.
However, I cannot figure out the math to get the pixels offset from that starting point, say to get this part of the spritesheet.
I either get a buffer overflow error, or the data is not correct at all. Does anyone have any idea on the correct math to manipulate the array to select all the latter parts of the image?
Upvotes: 0
Views: 47
Reputation: 631
The solution that I came to is this, assuming that the bitmap only stretches on the x axis (for my purposes).
static void getGlyphTexture(unsigned char *dataOut, unsigned char *dataIn, size_t bitmapWidth, size_t glyphSize, size_t index) {
for (size_t y = 0; y < glyphSize; y++) {
for (size_t x = 0; x < glyphSize; x++) {
dataOut[4 * ((glyphSize * y) + x) + 0] = dataIn[4 * ( bitmapWidth * y + glyphSize * index + x ) + 0];
dataOut[4 * ((glyphSize * y) + x) + 1] = dataIn[4 * ( bitmapWidth * y + glyphSize * index + x ) + 1];
dataOut[4 * ((glyphSize * y) + x) + 2] = dataIn[4 * ( bitmapWidth * y + glyphSize * index + x ) + 2];
dataOut[4 * ((glyphSize * y) + x) + 3] = dataIn[4 * ( bitmapWidth * y + glyphSize * index + x ) + 3];
}
}
}
Upvotes: 0