Jasmine
Jasmine

Reputation: 16175

embedding a PNG image in C++ as a vector or array

Can anyone point me in a direction so that I can take PNG images that I have and read them in and then store the data of the PNG Image into an array or vector (or some other data structure) so I can actually use that in my code instead of having to read in the PNG, etc?

I know I can use libPNG to read the image but once read in, I am a little stumped in how to take what is read in and convert it to a data structure I can use in my game.

So my thought is I can write a simple console program that I feed a list of PNG's, it reads them and spits out to a file the data for me to hardcode into a data structure in my actual game.

Upvotes: 1

Views: 2798

Answers (2)

Mercutio Calviary
Mercutio Calviary

Reputation: 184

After you have read the data in like Jason has said you could use a struct to contain the data for each pixel .

struct RGBAQUAD
{
     int Red;
     int Green;
     int Blue;
     int Alpha;
}

And then you could create a 2D array like such to represent all of the pixel structs as one contiguous image. But a drawback in this is having to manage memory.

RGBQUAD **arr = 0;
arr = new RGBQUAD *[y];
for(int i  = 0; i < y ; i++)
    arr[i] = new RGBQUAD[x];

alternatively you could pack a pixel into a single int to conserve ram space.

Upvotes: 1

user2448027
user2448027

Reputation: 1638

Load the image; take its width, height and bit depth (and possibly more info, if you need); read its color data, and save the information you extracted.

Example of what a data structure could be:

int width;
int height;
int bits;
std::vector<int> data[width*height*bits];

When you use that data structure:

/*
   Before these lines, you must get image dimensions and save them to width, height, depth variables. (either read them from somewhere or simply assign e.g. width=1024 if you know the width (I assume you do, as you're going to hardcode the image)).
*/
std::vector<int> sprite(width*height*depth);
for (int i = 0; i < width*height*depth; i++)
   // sprite[i] = (read pixel i from somewhere...);

Upvotes: 0

Related Questions