note 65979 deleted from function.imagecopyresampled by cmb
| From: | cmb@php.net | Date: | Sun, 19 May 2019 16:14:00 +0000 |
| Subject: | note 65979 deleted from function.imagecopyresampled by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211083@lists.php.net to get a copy of this message | ||
Note Submitter: Tyron Madlener (tyron.at)
----
Creating a thumbnail (120x90 pixel) of a big image (3000x2000 pixel) took me about 5 seconds with
imagecopyresampled()
Thats pretty much, so I tested a little how I could improve the speed. I found that imagecopyresized
is way faster but results in poor quality.
So I combined both - I first reduce the big image via imagecopyresized to 1024x768 pixel and then
create the small thumbnail via imagecopyresampled. The resulting quality is almost the same. In my
tests, resizing took only about 2.2 seconds now - twice as fast :)
I also tried using that bicubic image resizing function in some earlier post here, but it was only
faster when the thumbnails were smaller than 120x90 and the quality was not very good.
Here's the code if you wanna (I guess there are still a few possibilites to do some more
optimiztions tough):
<?php
function CreateThumb($file,$maxwdt,$maxhgt, $dest) {
list($owdt,$ohgt,$otype)=@getimagesize($file);
switch($otype) {
case 1: $newimg=imagecreatefromgif($file); break;
case 2: $newimg=imagecreatefromjpeg($file); break;
case 3: $newimg=imagecreatefrompng($file); break;
default: echo "Unkown filetype (file $file, typ $otype)"; return;
}
if($newimg) {
if($owdt>1500 || $ohgt>1200)
list($owdt, $ohgt) = Resample($newimg, $owdt, $ohgt, 1024,768,0);
Resample($newimg, $owdt, $ohgt, $maxwdt, $maxhgt);
if(!$dest) return $newimg;
if(!is_dir(dirname($dest)))
mkdir(dirname($dest));
switch($otype) {
case 1: imagegif($newimg,dest); break;
case 2: imagejpeg($newimg,$dest,90); break;
case 3: imagepng($newimg,$dest); break;
}
imagedestroy($newimg);
chmod($dest,0644);
}
}
function Resample(&$img, $owdt, $ohgt, $maxwdt, $maxhgt, $quality=1) {
if(!$maxwdt) $divwdt=0;
else $divwdt=Max(1,$owdt/$maxwdt);
if(!$maxhgt) $divhgt=0;
else $divhgt=Max(1,$ohgt/$maxhgt);
if($divwdt>=$divhgt) {
$newwdt=$maxwdt;
$newhgt=round($ohgt/$divwdt);
} else {
$newhgt=$maxhgt;
$newwdt=round($owdt/$divhgt);
}
$tn=imagecreatetruecolor($newwdt,$newhgt);
if($quality)
imagecopyresampled($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);
else
imagecopyresized($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);
imagedestroy($img);
$img = $tn;
return array($newwdt, $newhgt);
}
?>