所以我做了这个脚本,它使用PHP动态创建tumbnails并且它工作正常,但是我正在创建tumbnails的这些文件正在从用户上传。我有足够的验证来知道它正在上传哪种类型的图像。允许的一次是( JPG PNG GIF )我之前没有创建此脚本。
if (pathinfo($fileName,PATHINFO_EXTENSION) == 'png'){
$img = imagecreatefrompng($basePath.'/'.$fileName);
$width = imagesx($img);
$height = imagesx($img);
//Calculateing tumbnails size
$newWidth = 100;
$newHeight = floor($height*(100/$width));
//Create a new tempoary image
$tmpImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($tmpImage,$pathToTumb.'/'.$fileName);
}
if (pathinfo($fileName,PATHINFO_EXTENSION) == 'jpg'){
$img = imagecreatefromjpeg($basePath.'/'.$fileName);
$width = imagesx($img);
$height = imagesx($img);
//Calculateing tumbnails size
$newWidth = 100;
$newHeight = floor($height*(100/$width));
//Create a new tempoary image
$tmpImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagejpeg($tmpImage,$pathToTumb.'/'.$fileName);
}
if(pathinfo($fileName,PATHINFO_EXTENSION) == 'gif'){
$img = imagecreatefromgif($basePath.'/'.$fileName);
$width = imagesx($img);
$height = imagesx($img);
//Calculateing tumbnails size
$newWidth = 100;
$newHeight = floor($height*(100/$width));
//Create a new tempoary image
$tmpImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagegif($tmpImage,$pathToTumb.'/'.$fileName);
}
我发现非常重复的是有不同的方法为不同的格式做这个吗?
如果图像没有扩展名,如果文件名只是test而不是test.jpg
,我甚至想要这样做。答案 0 :(得分:1)
如果您发现自己复制并粘贴代码,则应将该代码转换为函数。您的代码可以重构如下:
switch (pathinfo($fileName, PATHINFO_EXTENSION)) {
case 'png':
$tmpImage = thumb(imagecreatefrompng($basePath.'/'.$fileName));
imagepng($tmpImage,$pathToTumb.'/'.$fileName);
break;
case 'jpg':
$tmpImage = thumb(imagecreatefromjpeg($basePath.'/'.$fileName));
imagejpeg($tmpImage,$pathToTumb.'/'.$fileName);
break;
case 'gif':
$tmpImage = thumb(imagecreatefromgif($basePath.'/'.$fileName));
imagegif($tmpImage,$pathToTumb.'/'.$fileName);
break;
}
function thumb($img) {
$width = imagesx($img);
$height = imagesx($img);
//Calculateing tumbnails size
$newWidth = 100;
$newHeight = floor($height*(100/$width));
//Create a new tempoary image
$tmpImage = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresized($tmpImage,$img,0,0,0,0,$newWidth,$newHeight,$width,$height);
return $tmpImage;
}
要检测没有文件扩展名的图片类型,您可以使用exif_imagetype()
,或者如果您的主机上没有,则使用getimagesize()
。