# HG changeset patch # User meillo@marmaro.de # Date 1213431307 -7200 # Node ID 8e71b54b6e1e87bcaab940e01a5ad68f08bed9e0 # Parent 7a8f72b27dc34ab707291b2e9d1b5ce939f46f60 made separate functions for calcsize and usage; pictures are not enlarged by default diff -r 7a8f72b27dc3 -r 8e71b54b6e1e resize-gd.c --- a/resize-gd.c Sat Jun 14 09:08:05 2008 +0200 +++ b/resize-gd.c Sat Jun 14 10:15:07 2008 +0200 @@ -23,8 +23,66 @@ Jpg, }; +struct size { + int w; + int h; +}; -int main(int argc, char* argv[]) { + +void +usage() { + puts("\ +usage: resize-gd [...]\n\ + (keeps aspect ratio, does not enlarge images)\n\ + resize-gd x [...]\n\ + (resizes to that size, enlarges if needed)\n\ +"); +} + + +struct size +calcsize(struct size opt, struct size img, int enlarge) { + struct size result; + + if (opt.h <= 0) { + /* keep aspect ratio */ + if (!enlarge && opt.w > img.w && opt.w > img.h) { + opt.w = (img.w > img.h) ? img.w : img.h; + } + if (img.w > img.h) { + result.w = opt.w; + result.h = opt.w * (1.0 * img.h / img.w); + } else { + result.h = opt.w; + result.w = opt.w * (1.0 * img.w / img.h); + } + } else { + result = opt; + } + return result; +} + + +int +validsize(char* sp) { + while (isdigit(*sp)) { + sp++; + } + if (*sp == 'x' && isdigit(*(sp+1))) { + sp++; + while (isdigit(*sp)) { + sp++; + } + } + if (*sp != '\0') { + return 0; + } + return 1; +} + + +int +main(int argc, char* argv[]) { int i; int w, h; int width, height; @@ -34,36 +92,27 @@ gdImagePtr im_out; FILE* in; FILE* out; - char* sep; + char* c; + struct size sizeopt, sizeimg, sizedest; if (argc < 3) { - puts("usage: resize-gd x \n\ - resize-gd (keeps aspect ratio)\n"); + usage(); exit(1); } - /* parse width and height */ - sep = argv[1]; - while (isdigit(*sep)) { - sep++; - } - if (*sep == 'x' && isdigit(*(sep+1))) { - sep++; - while (isdigit(*sep)) { - sep++; - } - } - if (*sep != '\0') { + if (!validsize(argv[1])) { fprintf(stderr, "Invalid form of size. Has to be or x.\n"); + usage(); exit(3); } - width = atoi(argv[1]); - sep = strstr(argv[1], "x"); - if (sep && sep[1] != '\0') { - height = atoi(sep + 1); + /* parse width and height */ + sizeopt.w = atoi(argv[1]); + c = strstr(argv[1], "x"); + if (c && c[1] != '\0') { + sizeopt.h = atoi(c + 1); } else { - height = -1; /* keep aspect ratio */ + sizeopt.h = -1; /* keep aspect ratio */ } @@ -100,22 +149,13 @@ fclose(in); - /* for keeping aspect ratio */ - if (height <= 0) { - if (im_in->sx > im_in->sy) { - w = width; - h = width * (1.0 * im_in->sy / im_in->sx); - } else { - h = width; - w = width * (1.0 * im_in->sx / im_in->sy); - } - } else { - w = width; - h = height; - } + /* calculate target size */ + sizeimg.w = im_in->sx; + sizeimg.h = im_in->sy; + sizedest = calcsize(sizeopt, sizeimg, 0); /* copy-resize the image */ - im_out = gdImageCreateTrueColor(w, h); + im_out = gdImageCreateTrueColor(sizedest.w, sizedest.h); gdImageCopyResampled(im_out, im_in, 0, 0, 0, 0, im_out->sx, im_out->sy, im_in->sx, im_in->sy); /* write image */