PHP图像调整大小/重新定位 - 加快速度

Pet*_*gad 1 php optimization performance

我写了一个小函数来获取一个url,并调整图像大小并将其存储在我的本地,但是当需要创建文件夹时脚本运行大约0.85秒,而调整大小时需要0.64秒.我目前支持JPEG和PNG,如下所示.

我想知道是否有更快的方法或我正在做的事情需要很长时间,因为我现在的时间对我来说是不可接受的,我真的希望让它更快地执行.

任何想法/想法都非常感谢.

谢谢!

  function getTime() {
      $timer = explode( ' ', microtime() );
      $timer = $timer[1] + $timer[0];
      return $timer;
  }

  function createThumb($thumb, $ids){
    $start = getTime();

    // File and new size
    $filename = $thumb;

    // Get new dimensions
    $img1 = getimagesize($filename);

    if ($img1[0] > $img1[1]) {
        $percentage = ('72' / $img1[0]);
    } else {
        $percentage = ('72' / $img1[1]);
    }
    $new_width = $img1[0] * $percentage;
    $new_height = $img1[1] * $percentage;

    // Resample
    $image_p = imagecreatetruecolor($new_width, $new_height);
    if($img1['mime']=='image/png'){
        $image = imagecreatefrompng($filename);
        imagealphablending($image_p, false);
        imagesavealpha($image_p,true);
        $transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
        imagefilledrectangle($image_p, 0, 0, $new_width, $new_height, $transparent);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $img1[0], $img1[1]);
    }
    else {
        $image = imagecreatefromjpeg($filename);
    }
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $img1[0], $img1[1]);



    $imgPath = '/foo/bar/location/'.$ids;
    $imgName ='';
    //category, product, support
    if(!is_dir($imgPath)) {
         mkdir($imgPath, 0777); 
         chmod($imgPath, 0777); 
    }

    if(!is_file($imgPath."/index.html")){
            $ourFileName = $imgPath."/index.html";
            $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
            fwrite($ourFileHandle,'<html><body>401</body></html>');
            fclose($ourFileHandle);     
    }

    // Output
    if($img1['mime']=='image/png'){
        $name = rand(1, 156406571337);
        $imgName = date("y_m_d_h_m_s").$name.'.png';
        imagepng($image_p, $imgPath.'/'.$imgName);

    } else {
        $name = rand(1, 156406571337);
        $imgName = date("y_m_d_h_m_s").$name.'.jpg';
        imagejpeg($image_p, $imgPath.'/'.$imgName, 100);
    }
    $end = getTime();
    echo  '<strong>createImage</strong>: '.round($end - $start,4).' seconden<br />';
    exit;
    return $imgName;

  }
Run Code Online (Sandbox Code Playgroud)

hob*_*ave 7

弗雷德里科,是GD图书馆,速度很慢.: - \我建议使用PHP ImageMagick库.语法是super braindead简单:

$image = new Imagick('image.jpg');
$image->thumbnailImage(100,0); // 100px wide, 0 = preserve aspect ratio
Run Code Online (Sandbox Code Playgroud)

我希望这是你的选择.