. ======================================================================*/ function kjwimage_create_thumbnail($infile, $outfile, $outx, $outy, &$characteristics = array()) { assert('strrpos($outfile, ".") !== false'); $outext = strtolower(substr($outfile, strrpos($outfile, '.') + 1)); if ($outext == 'jpeg') $outext = 'jpg'; assert('$outext == "gif" || $outext == "jpg" || $outext == "png"'); // Return-characteristics $characteristics = array(); // Open image if (($inimg = @imagecreatefrompng($infile))) { $inext = 'png'; } elseif (($inimg = @imagecreatefromjpeg($infile))) { $inext = 'jpg'; } elseif (($inimg = @imagecreatefromgif($infile))) { $inext = 'gif'; } else { return null; } // Image type $characteristics['input.extension'] = $inext; // Select scale (if $outx or $outy is null, we use inscale as outscale) $inx = imagesx($inimg); $iny = imagesy($inimg); $inscale = (float)$inx / (float)$iny; if ($outx !== null && $outy !== null) { $outscale = (float)$outx / (float)$outy; } elseif ($outx !== null && $outy === null) { $outscale = $inscale; $outy = $outx / $outscale; } elseif ($outx === null && $outy !== null) { $outscale = $inscale; $outx = $outy * $outscale; } else { assert(0); } // Create new image if (!($outimg = @imagecreatetruecolor($outx, $outy))) { imagedestroy($inimg); return null; } // In case we save as png, we use a transparent background, otherwise we use a white one. if ($outext == 'png') { imagesavealpha($outimg, true); imagealphablending($outimg, false); imagefill($outimg, 0, 0, imagecolorallocatealpha($outimg, 0xff, 0x00, 0xff, 127)); } else { imagefill($outimg, 0, 0, imagecolorallocate($outimg, 0xff, 0xff, 0xff)); } // Image size $characteristics['input.width'] = $inx; $characteristics['input.height'] = $iny; // If small scale difference, use full image and stretch it a bit. if (abs($outscale - $inscale) < 0.1) { $success = imagecopyresampled($outimg, $inimg, 0, 0, 0, 0, $outx, $outy, $inx, $iny); // If the image is too high, add space on the sides. } elseif ($outscale < $inscale) { $newy = (int)((float)$outx / $inscale); $success = imagecopyresampled($outimg, $inimg, 0, (int)(($outy - $newy) / 2), 0, 0, $outx, $newy, $inx, $iny); // If the image is too wide, add space on top/bottom. } else { $newx = (int)((float)$outy * $inscale); $success = imagecopyresampled($outimg, $inimg, (int)(($outx - $newx) / 2), 0, 0, 0, $newx, $outy, $inx, $iny); } imagedestroy($inimg); // Free memory early :) // Write image if ($success) { if ($outext == 'jpg') { $success = imagejpeg($outimg, $outfile); } elseif ($outext == 'png') { $success = imagepng($outimg, $outfile); } elseif ($outext == 'gif') { $success = imagegif($outimg, $outfile); } else { assert('false'); } } imagedestroy($outimg); // Free more return $success; } ?>