Debian Codegraph @

examples/copyrotated.c

raw
1 #include "gd.h"
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <math.h>
5
6 gdImagePtr loadImage(const char *name)
7 {
8 FILE *fp;
9 gdImagePtr im;
10
11 fp = fopen(name, "rb");
12 if (!fp) {
13 fprintf(stderr, "Can't open jpeg file\n");
14 return NULL;
15 }
16
17 im = gdImageCreateFromJpeg(fp);
18 fclose(fp);
19 return im;
20 }
21
22 int savePngImage(gdImagePtr im, const char *name)
23 {
24 FILE *fp;
25 fp = fopen(name, "wb");
26 if (!fp) {
27 fprintf(stderr, "Can't save png image fromtiff.png\n");
28 return 0;
29 }
30 gdImagePng(im, fp);
31 fclose(fp);
32 return 1;
33 }
34
35 int main(int argc, char **arg)
36 {
37 gdImagePtr im, im2;
38 int new_width, new_height;
39 double angle, a2;
40
41 if (argc < 3) {
42 fprintf(stderr, "Usage: copyrotated [angle in degree] [filename.png]\n");
43 return 1;
44 }
45 angle = strtod(arg[1], 0);
46 im = loadImage(arg[2]);
47
48 if (!im) {
49 fprintf(stderr, "Can't load PNG file <%s>", arg[1]);
50 return 1;
51 }
52
53 /*
54 cos adj hyp (cos = adjacent / hypothenus)
55 sin op hyp (sin adjacent / hypothenus)
56 + 10 pixels margin
57 */
58
59 /* to radian */
60 a2 = angle * .0174532925;
61
62 new_width = fabs(ceil(cos(a2) * gdImageSX(im))) +
63 fabs(sin(a2) * gdImageSY(im));
64 new_height = fabs(ceil(cos(a2) * gdImageSY(im))) +
65 fabs(sin(a2) * gdImageSX(im));
66
67
68 im2 = gdImageCreateTrueColor(new_width, new_height);
69 if (!im2) {
70 fprintf(stderr, "Can't create a new image");
71 gdImageDestroy(im);
72 return 1;
73 }
74
75 gdImageAlphaBlending(im2, 0);
76 gdImageFilledRectangle(im2, 0, 0, gdImageSX(im2), gdImageSY(im2), gdTrueColorAlpha(127,0,0,127));
77
78 gdImageCopyRotated(im2, im, new_width/2, new_height/2, 0, 0, gdImageSX(im), gdImageSY(im), angle);
79 gdImageSaveAlpha(im2, 1);
80 if (!savePngImage(im2, "rotated.png")) {
81 fprintf(stderr, "Can't save PNG file rotated.png");
82 gdImageDestroy(im);
83 gdImageDestroy(im2);
84 return 1;
85 }
86
87 gdImageDestroy(im2);
88 gdImageDestroy(im);
89 return 0;
90 }