Resize images with PHP, support PNG, JPG
function resize($newWidth, $targetFile, $originalFile) { $info = getimagesize($originalFile); $mime = $info['mime']; switch ($mime) { case 'image/jpeg': $image_create_func = 'imagecreatefromjpeg'; $image_save_func = 'imagejpeg'; $new_image_ext = 'jpg'; break; case 'image/png': $image_create_func = 'imagecreatefrompng'; $image_save_func = 'imagepng'; $new_image_ext = 'png'; break; case 'image/gif': $image_create_func = 'imagecreatefromgif'; $image_save_func = 'imagegif'; $new_image_ext = 'gif'; break; default: throw new Exception('Unknown image type.'); } $img = $image_create_func($originalFile); list($width, $height) = getimagesize($originalFile); $newHeight = ($height / $width) * $newWidth; $tmp = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); if (file_exists($targetFile)) { unlink($targetFile); } $image_save_func($tmp, "$targetFile.$new_image_ext");}
I've written a class that will do just that and is nice and easy to use. It's called
PHP Image Magician
$magicianObj = new imageLib('racecar.jpg');$magicianObj -> resizeImage(100, 200);$magicianObj -> saveImage('racecar_convertd.png', 100);
It supports Read and Write (including converting) the following formats
- jpg
- png
- gif
- bmp
And can read only
- psd's
Example
// Include PHP Image Magician libraryrequire_once('php_image_magician.php');// Open JPG image$magicianObj = new imageLib('racecar.jpg');// Resize to best fit then crop$magicianObj -> resizeImage(100, 200, 'crop');// Save resized image as a PNG$magicianObj -> saveImage('racecar_small.png');
You can try this. Currently it's assuming the image will always be a jpeg. This will allow you to load a jpeg, png, or gif. I haven't tested but it should work.
function resize($newWidth, $targetFile) { if (empty($newWidth) || empty($targetFile)) { return false; } $fileHandle = @fopen($this->originalFile, 'r'); //error loading file if(!$fileHandle) { return false; } $src = imagecreatefromstring(stream_get_contents($fileHandle)); fclose($fileHandle); //error with loading file as image resource if(!$src) { return false; } //get image size from $src handle list($width, $height) = array(imagesx($src), imagesy($src)); $newHeight = ($height / $width) * $newWidth; $tmp = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); //allow transparency for pngs imagealphablending($tmp, false); imagesavealpha($tmp, true); if (file_exists($targetFile)) { unlink($targetFile); } //handle different image types. //imagepng() uses quality 0-9 switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) { case 'jpg': case 'jpeg': imagejpeg($tmp, $targetFile, 95); break; case 'png': imagepng($tmp, $targetFile, 8.5); break; case 'gif': imagegif($tmp, $targetFile); break; } //destroy image resources imagedestroy($tmp); imagedestroy($src);}