Home > Article > Backend Development > php simple thumbnail class|image.class.php_PHP tutorial
How to use:
$img = new iamge;
$img->resize('dstimg.jpg', 'srcimg.jpg', 300, 400);
Note: This is scaled according to the proportion. dstimg.jpg is the target file, srcimg.jpg is the source file, and the following is the width and height of the target file
$img->thumb('dstimg.jpg', 'scrimg.jpg', 300, 300);
Note: This is a proportional thumbnail. For example, it is commonly used in avatar thumbnails. dstimg.jpg is the target file, srcimg.jpg is the source file, and the following is the width and height of the target file
This is only troublesome for the GD library. If you use Imagick, you only need two functions to implement the above functions. You can find it by checking the documentation.
class image{
public function resize($dstImg, $srcImg, $dstW, $dstH){
list($srcW, $srcH) = getimagesize($srcImg);
$scale = min($dstW/$srcW, $dstH/$srcH);
$newW = round($srcW * $scale);
$newH = round($srcH * $scale);
$newImg = imagecreatetruecolor($newW, $newH);
$srcImg = imagecreatefromjpeg($srcImg);
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $srcW, $srcH);
imagejpeg($newImg, $dstImg);
}
public function thumb($dstImg, $srcImg, $dstW, $dstH){
list($srcW, $srcH) = getimagesize($srcImg);
$scale = max($dstW/$srcW, $dstH/$srcH);
$newW = round($dstW/$scale);
$newH = round($dstH/$scale);
$x = ($srcW - $newW)/2;
$y = ($srcH - $newH)/2;
$newImg = imagecreatetruecolor($dstW, $dstH);
$srcImg = imagecreatefromjpeg($srcImg);
imagecopyresampled($newImg, $srcImg, 0, 0, $x, $y, $dstW, $dstH, $newW, $newH);
imagejpeg($newImg, $dstImg);
}
}
function createFromType($type, $srcImg){
$function = "imagecreatefrom$type";
return $function($srcImg);
}
//In order to solve the problem of different image formats