在 C 中将 ppm 图像向右旋转 90 度

Rotating a ppm image 90 degrees to the right in C

我在向右旋转 PPM 图像时遇到以下问题 结果图像中的前两行是黑色(或彩虹中的某种颜色)

这是设置图像缓冲区的代码(变量 g_Width 和 g_height 由函数设置)

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

这是传入指针的函数

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;
}

如果我打印图像缓冲区,结果很好,但如果我旋转它,结果是这样的(注意前两行像素)

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

好像最后两行根本没有交换,请帮忙

编辑:我至少解决了第二条黑线,但我仍然需要帮助 最后一行

如前所述,您混合了第一行(并溢出)

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;
}

这会以一种方式旋转它(删除不必要的括号)

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

但是您的代码建议您以另一种方式使用它,并且该代码缺少 -1,导致在一条边上剪下一条线,在另一条边上剪下一条未定义的线。

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];
    }
}