【发布时间】:2014-11-11 01:42:17
【问题描述】:
我有以下 php 代码,它可以调整 cbimages 文件夹中的图像大小并在另一个文件夹 cbimages/thumbs/ 中创建缩略图图像
<?php
//Maximize script execution time
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = '/var/www/example.com/public_html/cbimages/'; //Source Image Directory End with Slash
$DestImagesDirectory = '/var/www/example.com/public_html/cbimages/thumbs/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 80; //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(resizeImage($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);
}
//Function that resizes image.
function resizeImage($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);
switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
case 'image/png':
case 'image/gif':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
default:
return false;
}
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
// copy file
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
return true;
}
}
}
?>
该脚本在我使用 ubuntu 14.04 的本地开发环境中运行良好并且运行速度很快。在我的 ubuntu 14.04 服务器上,杯子的使用率高达 100%,需要时间才能完成。
运行脚本花费了太多时间,CPU 使用率高达 100%。每次我启动这个脚本时,它都会开始调整所有图像的大小..即使是那些调整大小的。
如何优化脚本??
请求帮助。提前致谢。
【问题讨论】:
-
禁用的功能不相关。查看哪些扩展是活动的或缺少的。比较两台服务器的
php_info()。 -
@Havenard 没有其他区别...
-
比较
php.ini文件。有比较工具吗? -
没有循环怎么办?我个人建议使用 SPL 文件系统或目录迭代器,甚至使用 scandir 代替 openDir 和所有那些 jaz,如果你没有 GD,你可能会立即知道,很可能你有一个无限循环
-
用 php 创建缩略图确实很痛苦,即使在本地环境中也是如此。我会在我的图书馆之间寻找一个我为此准备的课程,并将其作为答案发布,看看它是否更快,但我对此表示怀疑。