2015-04-14 64 views
0

我有以下問題與PPM圖像向右旋轉 前兩行的結果圖像中是黑色的(或從彩虹一些顏色)旋轉ppm的圖像90度到右側用C

下面是設置圖像緩衝區(變量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; 
} 
功能的代碼3210

如果我打印圖像緩衝區它出來就好了,但如果我旋轉它,它出來像這樣(注意第2行像素)

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

就好像最後兩行AREN 「T在所有被交換,請大家幫忙

編輯:我解決了第二個黑線至少,但我仍然需要與 最後一行幫助

+1

您必須初始化所有緩衝區。例如'buffer [0]'未設置。也許'緩衝區[(g_height * j)+(g_height-i - 1)]' –

+0

完美解析,謝謝:) – darkflame470

回答

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

這將旋轉的一種方式(去除不必要的括號)

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