我正在尝试使用php gd库压缩和调整图像大小。几乎所有关于so和其他地方的答案都是一样的,但是对于我的解决方案,png没有被正确地转换,一些jpg给出了奇怪的结果。
这是我正在使用的代码:
public function resizeImages() {
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = FCPATH . 'design/img/test/'; //Source Image Directory End with Slash
$DestImagesDirectory = FCPATH . 'design/img/test/thumb/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 90; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){
$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = @getimagesize($imagePath);
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if (resize_image($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
{
echo $file.' resize Success!<br />';
/*
Now Image is resized, may be save information in database?
*/
} else {
echo $file.' resize Failed!<br />';
}
}
}
closedir($dir);
}
}
resize_image函数如下所示:
function resize_image($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
$imagetype = strtolower(image_type_to_mime_type($type));
switch($imagetype)
{
case 'image/jpeg':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
case 'image/png':
$NewImage = imagecreatefrompng($SrcImage);
break;
default:
return false;
}
//allow transparency for pngs
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
switch ($imagetype) {
case 'image/jpeg':
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
case 'image/png':
if(imagepng($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
default:
return false;
}
return true;
}
}
每一个PNG都不工作,它只返回一个0字节的文件并且“不支持文件类型”,即使在Windows中该类型被识别为.png…
一些jpg也返回了一个奇怪的结果,请参见下面的屏幕截图,它指出了我关于png和一些jpg的问题:
最佳答案
1)不要使用getimagesize来验证文件是否是有效的图像,要提到手册:
不要使用getImageSize()检查给定文件是否为有效图像。请改用专门构建的解决方案,如fileinfo扩展名。
$checkValidImage = exif_imagetype($imagePath);
if(file_exists($imagePath) && ($checkValidImage == IMAGETYPE_JPEG || $checkValidImage == IMAGETYPE_PNG))
2)虽然
imagejpeg()
接受0到100之间的质量,imagepng()
想要0到9之间的值,但您可以这样做:if(imagepng($NewCanves,$DestImage,round(($Quality/100)*9)))
3)使用
readdir ()
时,应跳过当前目录.
和父目录..
while(($file = readdir($dir))!== false){
if ($file == "." || $file == "..")
continue;
关于php - 使用PHP GD lib压缩和调整图像大小不适用于png和jpg的奇怪结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57923865/