php - 使脚本性能更高效

标签 php jquery

我有一个脚本可以制作目录中图片的缩略图。但它的执行时间太长(目录中大约有 170 张图像)。

脚本由ajax请求调用。完成 70% 后,我收到一条错误消息,可能是由于超时(大约需要 3-4 分钟)。

我该如何解决这个问题?

function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
 // open the directory
 $dir = opendir( $pathToImages );

 // loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' ) 
{

  // load image and get image size
  $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
  $width = imagesx( $img );
  $height = imagesy( $img );

  // calculate thumbnail size
  $new_width = $thumbWidth;
  $new_height = floor( $height * ( $thumbWidth / $width ) );

  // create a new temporary image
  $tmp_img = imagecreatetruecolor( $new_width, $new_height );

  // copy and resize old image into new image 
  imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

  // save thumbnail into a file
   imagejpeg( $tmp_img, "{$pathToThumbs}thumb_{$fname}" );
   }
  }
   // close the directory
  closedir( $dir );
  }

  createThumbs($directory,$directory."/thumbs/",150);

ajax调用;

   var ajaxr=$.ajax({
  type: "POST",
  url: "after_upload.php",
  timeout:600,
  beforeSend: function() {
  $("#result").html('<div align="center"><h2>מבצע עיבוד נתונים יקח זמן ,חכה..תכין קפה בנתיים      ותעשן סיגריה</h2><div><img src="loader.gif"/><div dir="rtl" style="margin:15px;">טוען מידע וממיר תמונות... <button id="cancel" style="padding:5px;">בטל פעולה ותחזור חזרה [X]</button></div></div>  </div>');
                        },
  success: function(data){
       $("#result").html(data);
  },
  error: function(xhr, textStatus, errorThrown) {
                             $("#result").html(textStatus);
                        }
  });

现在,将 ajax 调用中的超时时间增加到 3000,并且由于某种原因立即返回超时错误。如果我从调用中删除超时属性..它会执行调用和脚本执行..但只有 70%工作完成..完成返回空错误...

更新:..我现在执行所有操作以缩短脚本执行时间:控制台返回 404 Not Found..

最佳答案

使缩略图的创建循环运行,并在每次循环后从服务器内存中删除先前的资源。

imagedestroy($thumb);
imagedestroy($source);

这会很有帮助,我刚刚完成了非常相似的事情。

关于php - 使脚本性能更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16414974/

相关文章:

javascript - jquery,javascript 在 Bootstrap 中不工作

javascript - 如何找到页脚中 &lt;script&gt; 的来源?

javascript - 无限函数调用

javascript - 在 jqGrid 渲染后隐藏列(标题和行)

jquery - 将函数应用于类或通过each() 之间的区别

php - 在事务中为两个表插入相同的键(1.主表2.外表)

语言表的 php 空结果

php - 将支付宝实现到 OpenCart

php - 使用 PHPMailer 发送电子邮件和旋转图像

php - 如何在 CakePHP 中手动转义 mySQL 数据库插入的 bool 值?