user8314628
user8314628

Reputation: 2042

How to read pixels of an image in c?

Suppose our bitmap image has height M and width N. We'll always assume in this lab that the width N is a multiple of 4, which simplifies the byte layout in the file. For this image, the pixel array stores exactly 3 x N x M bytes, in the following way:

Each group of 3 bytes represents a single pixel, where the bytes store the blue, green, and red colour values of the pixel, in that order.

Pixels are grouped by row. For example, the first 3 x N bytes in the pixel array represent the pixels in the top-most row of the image.

pixel_array_offset is where the pixel array starts.

A struct pixel is given as following:

struct pixel {
    unsigned char blue;
    unsigned char green;
    unsigned char red;
};

And here is the requirement for implementing the function:

/*
 * Read in pixel array by following these instructions:
 *
 * 1. First, allocate space for m "struct pixel *" values, where m is the
 *    height of the image.  Each pointer will eventually point to one row of
 *    pixel data.
 * 2. For each pointer you just allocated, initialize it to point to
 *    heap-allocated space for an entire row of pixel data.
 * 3. ...
 * 4. ...
 */
struct pixel **read_pixel_array(FILE *image, int pixel_array_offset, int width, int height) {

}

For the first step, allocate space for m "struct pixel *" values. I think it is actually allocating space for an array of pixel values. So I put

unsigned char **ptrs = height * malloc(sizeof(struct pixel));

For the second step, I don't quite understand what I should do. I think I need a for loop to allocate space for all rows of pixel data. But I have no idea what I should put inside.

for (int i=0, i<height, i++) {

        }

Upvotes: 4

Views: 11092

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

Since you want to allocate a 2D array, you first need to allocate an array of struct pixel *:

struct pixel **ptrs = malloc(height * sizeof(struct pixel*));

There are several changes here to note:

  1. You are allocating pointers to struct pixel, not unsigned char.
  2. malloc() returns a pointer. Multiplying a pointer by an integer is invalid.
  3. The multiplication goes in the parentheses because it helps calculate the correct number of bytes to allocate.

Next you need to allocate an array of struct pixel for each row in the 2D array:

for (int i=0, i<height, i++) {
    ptrs[i] = malloc(width * sizeof(struct pixel));
}

Now the array is completely allocated and you can fill it in with data:

ptrs[5][6] = { 255, 0, 0}; // a blue pixel

Finally remember to free() all of your pointers before you exit your program:

for (int i=0, i<height, i++) {
    free(ptrs[i]);
}

free(ptrs);

Upvotes: 5

Related Questions