Search code examples
cimagerotationppm

Rotating a ppm image 90 degrees to the right in C


I have the following problem with rotating the PPM image to the right The first two lines in the result image are black (or some color from the rainbow)

Here's the code that sets the buffer for the image (the variables g_Width and g_height are set by a function)

struct pixel *image = malloc(sizeof(struct pixel) * g_width * g_height);

here's the function with the pointer passed into it

void rotate90(struct pixel *img) {
    int i, j, size, th;
    size = sizeof(struct pixel) * g_width * g_height;
    struct pixel *buffer = malloc(size);

    if (buffer == NULL) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < g_height; i++) {
        for (j=0; j < g_width; j++) {
            buffer[(g_height*j)+(g_height-i)] = img[(g_width*i) + j];
        }
    }

    //copy the buffer into the image pointer
    memcpy(img, buffer, size);

    //free the buffer and swap the width and height around
    free(buffer);
    th = g_height;
    g_height = g_width;
    g_width = th;
}

If I print the image buffer it comes out just fine, but if I rotate it it comes out like this (note the first 2 lines of pixels)

https://www.dropbox.com/s/vh8l6s26enbxj42/t3.png?dl=0

it's as if the last 2 lines aren't being swapped at all, please help

EDIT: I solved the second black line at least, but I still need help with the last line


Solution

  • As said you mix the first line (and overflow)

    void rotate90(struct pixel *img) {
        int i, j, size, th;
        size = sizeof(struct pixel) * g_width * g_height;
        struct pixel *buffer = malloc(size);
    
        if (buffer == NULL) {
            fprintf(stderr, "Unable to allocate memory\n");
            exit(EXIT_FAILURE);
        }
    
        for (i = 0; i < g_height; i++) {
            for (j=0; j < g_width; j++) {
                buffer[(g_height*j)+(g_height-i -- 1)] = img[(g_width*i) + j];
            }
        }
    
        //copy the buffer into the image pointer
        memcpy(img, buffer, size);
    
        //free the buffer and swap the width and height around
        free(buffer);
        th = g_height;
        g_height = g_width;
        g_width = th;
    }