0

我是新来的,所以这将是我的第一篇文章!

我在下面有这个功能,即将四个图像合并为一个。它有效,但需要将近 20 秒。有什么办法可以加快这个速度吗?感谢所有帮助!

<?php

$images = $_GET['i']; 
$nb = $_GET['nb']; 

if ($nb == '4') { 
   $dest = imagecreatefrompng('files/template_collage_' . $nb . '.png'); 
    $image_files = explode('|', $images); 
    $i = 1; 

    foreach ($image_files as $image_file) { 

        $image_source = imagecreatefromjpeg($image_file); 
        $size = getimagesize($image_file); 
        $image_new = imagecreatetruecolor(612,612); 
        imagecopyresampled($image_new,$image_source,0,0,0,0,612,612,$size[0],$size[1]); 

        if ($i == 1) { 
            imagecopymerge($dest, $image_new, 0, 0, 0, 0, 612, 612, 100); 

        } else if ($i == 2) { 
            imagecopymerge($dest, $image_new, 612, 0, 0, 0, 612, 612, 100); 

        } else if ($i == 3) { 
            imagecopymerge($dest, $image_new, 0, 612, 0, 0, 612, 612, 100); 

        } else if ($i == 4) { 
            imagecopymerge($dest, $image_new, 612, 612, 0, 0, 612, 612, 100); 

        } 

        $i++; 

        imagedestroy($image_source); 
        imagedestroy($image_new); 
        $size = ''; 
    } 


    // Output and free from memory 
    header('Content-Type: image/png'); 
    header('Content-Disposition: inline; filename=collage_card.png'); 
    imagejpeg($dest, null, 100); 

    imagedestroy($dest); 


}  

?>

以下更新:

我改为 imagecopyresampled 并摆脱了 $image_new。仍然没有改善,每个循环大约需要 4.5 秒。

<?php

if ($nb == '4') {

$dest = imagecreatefrompng('files/template_collage_' . $nb . '.png');
$image_files = explode('|', $images);
$i = 1;

foreach ($image_files as $image_file) {

    $image_source = imagecreatefromjpeg($image_file);
    $size = getimagesize($image_file);

    if ($i == 1) {
        imagecopyresampled($dest, $image_source, 0, 0, 0, 0, 612, 612, $size[0],$size[1]);

    } else if ($i == 2) {
        imagecopyresampled($dest, $image_source, 612, 0, 0, 0, 612, 612, $size[0],$size[1]);

    } else if ($i == 3) {
        imagecopyresampled($dest, $image_source, 0, 612, 0, 0, 612, 612, $size[0],$size[1]);

    } else if ($i == 4) {
        imagecopyresampled($dest, $image_source, 612, 612, 0, 0, 612, 612, $size[0],$size[1]);

    }

    $i++;

    imagedestroy($image_source);
    $size = '';
}


// Output and free from memory
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename=collage_card.jpg');
imagejpeg($dest, null, 100);

imagedestroy($dest);


}

?>
4

1 回答 1

0

不需要中间体$image_new

if ($i == 2) {
  imagecopyresampled($dest, $image_source,
    612, 0,           // target position
    0, 0,             // source position
    612, 612,         // target size
    $size[0],$size[1] // source size
  );
}

此外,如果一个复杂的操作花费的时间太长,第一步是衡量复杂操作的哪一部分实际上是造成这种情况的原因。一些合适的电话microtime()将帮助您解决这个问题。

于 2013-11-10T13:21:48.453 回答