+function create_thumbnail_or_copy ($filename, $destfile) {
+ try {
+ $thumbnail_ok = create_thumbnail ($filename, $destfile);
+ } catch (Exception $e) {
+ $thumbnail_ok = false;
+ }
+ if (!$thumbnail_ok) {
+ if (!copy ($filename, $destfile)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function create_thumbnail ($filename, $destfile) {
+ if (!function_exists ("imagecreatefromjpeg")
+ || !function_exists ("imagecreatefrompng")) {
+ return false;
+ }
+ $ext = strtolower (ext_safe ($filename));
+ if ($ext == "jpg" || $ext == "jpeg") {
+ $image = imagecreatefromjpeg ($filename);
+ } else if ($ext == "png") {
+ $image = imagecreatefrompng ($filename);
+ } else {
+ return false;
+ }
+
+ if ($image === false) {
+ return false;
+ }
+
+ if (defined (THUMBSMAXSIZE) && (THUMBSMAXSIZE > 0)) {
+ $thumbsmaxsize = THUMBSMAXSIZE;
+ } else {
+ $thumbsmaxsize = 400; // default value;
+ }
+
+ $width = imageSX ($image);
+ $height = imageSY ($image);
+ if (($width <= $thumbsmaxsize) || ($height <= $thumbsmaxsize)) {
+ return false;
+ }
+
+ if ($width > $height) {
+ $thumb_width = $thumbsmaxsize;
+ $thumb_height = $height * ($thumbsmaxsize / $width);
+ } else if ($width < $height) {
+ $thumb_width = $width * ($thumbsmaxsize / $height);
+ $thumb_height = $thumbsmaxsize;
+ } else if ($width == $height) {
+ $thumb_width = $thumbsmaxsize;
+ $thumb_height = $thumbsmaxsize;
+ }
+
+ $thumb_image = ImageCreateTrueColor ($thumb_width, $thumb_height);
+ if ($thumb_image === false) {
+ return false;
+ }
+ if (!imagecopyresampled ($thumb_image, $image, 0, 0, 0, 0,
+ $thumb_width, $thumb_height, $width, $height)) {
+ return false;
+ }
+
+ if ($ext == "jpg" || $ext == "jpeg") {
+ if (!imagejpeg ($thumb_image, $destfile, 100)) {
+ return false;
+ }
+ } else if ($ext == "png") {
+ if (!imagepng ($thumb_image, $destfile)) {
+ return false;
+ }
+ }
+
+ imagedestroy ($image);
+ imagedestroy ($thumb_image);
+
+ return true;
+}