+// Make a thumbnail of the image (to width: 120 pixels)
+// Returns true if success, false otherwise.
+function resizeImage($filepath)
+{
+ if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
+
+ // Trick: some stupid people rename GIF as JPEG... or else.
+ // So we really try to open each image type whatever the extension is.
+ $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
+ $im=false;
+ if (strpos($header,'GIF8')==0) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
+ if (strpos($header,'PNG')==1) $im = imagecreatefrompng($filepath);
+ if (strpos($header,'JFIF')) $im = imagecreatefromjpeg($filepath);
+ if (!$im) return false; // Unable to open image (corrupted or not an image)
+ $w = imagesx($im);
+ $h = imagesy($im);
+ $nw = 120; // Desired width
+ $nh = floor(($h*$nw)/$w); // Compute new width/height while keeping ratio
+ // Resize image:
+ $im2 = imagecreatetruecolor($nw,$nh);
+ imagecopyresampled($im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h);
+ imageinterlace($im2,true); // For progressive JPEG.
+ $tempname=$filepath.'_TEMP.jpg';
+ imagejpeg($im2, $tempname, 90);
+ imagedestroy($im);
+ imagedestroy($im2);
+ rename($tempname,$filepath); // Overwrite original picture with thumbnail.
+ return true;
+}
+