Frage

i am coding in C and i have to work with png images, so i work with libpng library. In my project i use this structure:

png_bytep *row_pointers; /* <-- to declare the pointer that will contain the image 
                           and this to initialize the pointer to contain the image. */

row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * height); 
for(int y = 0; y < height; y++) {
    row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png,info)); 
}

My problem is: after this piece of code my image is copyed in row_pointers and i want to copy it in a png_byte map[x][y] so i can work easly pixel for pixel. Someone can help me? Thanks

War es hilfreich?

Lösung

Ok. That is pointer to pointer!

png_bytep = pointer to png_byte

If you eliminate png_bytep and just use png_byte your code will look like this.

int height = 10;
int width = 20;

png_byte **row_pointers;
row_pointers = (png_byte**)malloc(sizeof(png_byte*) * height);  <-- This is basically your number of rows.. ie height of your matrix.
for(int y = 0; y < height; y++) 
{
    row_pointers[y] = (png_byte*)malloc(sizeof(png_byte)*width); <-- This is representing number of elements in each row.. so width. 

}

Assuming your structure have two ints x and y. you must be filing data as below..

for(int i=0;i< height;i++)
{
    for (int j=0;j<width;j++)
    {
        row_pointers[i][j].x = i*j;
        row_pointers[i][j].y = i*j;
    }
}

Assuming your map also have similar structure. This is how you copy data..

for(int i=0;i< height;i++)
{
    for (int j=0;j<width;j++)
    {
        map[i][j].x = row_pointers[i][j].x;
        map[i][j].y = row_pointers[i][j].y;
    }
}

Andere Tipps

Have a look at pnm2png.c in libpng's contrib/pngminus directory.

In this code, "png_pixels" is a simple array that holds all the pixels, and row_pointers is an array of pointers that point to the beginning of each row within png_pixels:

/* row_bytes is the width x number of channels x (bit-depth / 8) */
  row_bytes = width * channels * ((bit_depth <= 8) ? 1 : 2);

  png_pixels = (png_byte *) malloc (row_bytes * height * sizeof (png_byte))

/* set the individual row_pointers to point at the correct offsets */
  for (i = 0; i < (height); i++)
    row_pointers[i] = png_pixels + i * row_bytes;

/* now we can go ahead and just read the whole image */
  png_read_image (png_ptr, row_pointers);

Once png_read_image completes, you can easily work with your pixels in the png_pixels array.

Notice that there is only one "malloc", which allocates png_pixels. Instead of doing a separate "malloc" for each row, this code calculates the values of the row_pointers.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top