0

I am using the PHP function imagecopyresample and imagecopy to rotate and merge two images. Both images are around 2480px by 3508px and can vary between 3MB - 10MB. At the moment it is taking around 30 seconds to merge the two, below is my code.

I was just wondering if there is a better way of doing this? I don't need the images displayed on screen and can actually be done in the background while the user is still navigating the site.

Thanks in advance

 $photoFrame    = imagecreatetruecolor(3508,2480);

        $trans_colour   = imagecolorallocate($photoFrame, 255, 255, 255);
        imagefill($photoFrame, 0, 0, $trans_colour);

        for($i = 0; $i < $count_images; ++$i){
            $insert         = $res['images'][$i]['src'];
            $extension      = substr(strrchr($insert,'.'),1);
            $photoFrame2Rotation = (180-$res['images'][$i]['rotation']) + 180;

            $photo2         = imagecreatefrompng($insert);}
            $foto2W         = imagesx($photo2);
            $foto2H         = imagesy($photo2);
            $photoFrame2W   = $res['images'][$i]['width'];
            $photoFrame2H   = $res['images'][$i]['height'];

            $photoFrame2TOP = $res['images'][$i]['top'];
            $photoFrame2LEFT= $res['images'][$i]['left'];

            $photoFrame2    = imagecreatetruecolor($photoFrame2W,$photoFrame2H);
            $trans_colour   = imagecolorallocatealpha($photoFrame2, 0, 0, 0, 127);
            imagefill($photoFrame2, 0, 0, $trans_colour);

            imagecopyresampled($photoFrame2, $photo2, 0, 0, 0, 0, $photoFrame2W, $photoFrame2H, $foto2W, $foto2H);

            imagesavealpha($photoFrame2, true);

            $blue = imagecolorallocate($photoFrame2, 0, 0,255);
            imagecolortransparent($photoFrame2, $blue);

            imagecopy($photoFrame, $photoFrame2,$photoFrame2LEFT, $photoFrame2TOP, 0, 0, imagesx($photoFrame2), imagesy($photoFrame2));
        }

    $cachefile = "userdir/".$value.".png"; 

    imagepng($photoFrame, $cachefile, 1);
    imagedestroy($photoFrame);
jmgibbo
  • 97
  • 1
  • 10
  • I don't see where you release the memory for the loaded image? You should add a call to `imagedestroy` in your loop to release the memory associated with the resource returned from `imagecreatefrompng` – Cyclonecode Nov 24 '12 at 18:57
  • @KristerAndersson sorry I missed it out of the code. I have now added it. If I should be releasing the loaded image somewhere else in the code could you point it out for me. Thank you – jmgibbo Nov 24 '12 at 19:06
  • You should also relase the memory for `$photo2 and $photoFrame2` inside your loop. – Cyclonecode Nov 24 '12 at 19:12
  • Does this answer your question? [Efficient JPEG Image Resizing in PHP](https://stackoverflow.com/questions/12661/efficient-jpeg-image-resizing-in-php) – Lorenz Meyer Apr 08 '21 at 13:17

0 Answers0