Question

I am trying to rotate a PPM image 90 degrees. I am currently able to rotate the image 180 degrees. I am not sure on how to do this.

I know that the height and width are swapped, but I am not sure where to go from there.

void write_ppm_image(const char *filename, Image_ppm *img)
{
FILE *fp;
//open file for output
fp = fopen(filename, "wb");
if (!fp) {
    fprintf(stderr, "Unable to open file '%s'\n", filename);
    exit(1);
}

//write the header file
//image format
fprintf(fp, "P6\n");

//comments
fprintf(fp, "# Created by %s\n",CREATOR);

//image size
fprintf(fp, "%d %d\n",img->x,img->y);

// rgb component depth
fprintf(fp, "%d\n",RGB_COMPONENT_COLOR);

// pixel data
fwrite(img->data, 3 * img->x, img->y, fp);
fclose(fp);
}


 void rotatePPM(Image_ppm *img)
 {
int x = 0, y = 0;
int size = img->x*img->y;
int width = img->x;
int height = img->y;

if(img)
{

    for(i=0;i<size;i++)
    {
        int temp = img->data[i].red;
        int temp_one = img->data[i].green;
        int temp_two = img->data[i].blue;
        img->data[i].red = img->data[size].red;
        img->data[i].green = img->data[size].green;
        img->data[i].blue = img->data[size].blue;
        img->data[size].red = temp;
        img->data[size].green = temp_one;
        img->data[size].blue = temp_two;
        size--;
    }

}
 }

 int main()
 {
char  filename[256];
printf("Enter the name of a PPM image file: \n");
scanf("%s",filename);
Image_ppm *image;
image = read_ppm_image(filename);
rotatePPM(image);
write_ppm_image("can_bottom3.ppm",image);
printf("Press any key...");
getchar();
}
Was it helpful?

Solution

While I have never implemented any rotation algorithm, I think it would help to actually do it on paper first...

Draw a rectangle on a squared paper, where each square represents a pixel. Label each square with the coordinates of the pixels. Then turn the paper 90 degrees, and draw a second equally large rectangle, again with each "pixel" labeled with the coordinates.

Now when you turn the paper back so the first rectangle is normal, you can easily see where to put the pixels in the output (second) rectangle.

It shouldn't be too hard to find a general algorithm for that.

OTHER TIPS

Your approach seems very painful, and is only geared towards PPM.

Instead, you could simply use ImageMagick mogrify or GraphicsMagick gm mogrify utility. You could download statically compiled version of GraphicsMagick gm with size less than 2MB.

gm can be considered "swiss army knife" for any image manipulations. Aside from making it easy, it will support not only PPM, but almost any other known graphics format, effortlessly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top