0

I am developing a PHP script that will optimize all images in a zip file. I have written a function to optimize a single image. How can I this function so that all the images will be optimized at the same time. I don't know whether its multitasking or multithreading.

The current way I'm doing it is optimizing one by one which is taking too much time. Is there any way we can run multiple functions at the same time?

<?php
$img1  = "1.jpg";
$img2  = "2.jpg";
$img3  = "3.jpg";

optimize($img1);  // \
optimize($img2);  //  execute these functions in same time
optimize($img3);  // /

function optimize($image)
{
  // code for optimization
}
?>
Gijo Varghese
  • 11,264
  • 22
  • 73
  • 122
  • possible duplicate of [Running multiple functions in php](http://stackoverflow.com/questions/1906470/running-multiple-functions-in-php) – Funk Forty Niner Apr 23 '16 at 12:27

2 Answers2

1

you can user pcntl_fork() function, but it creates new process. PHP is not best choice, if you want to code multithreading programs.

vengek
  • 36
  • 3
  • is there any disadvantages in using pcntl_fork() ? Also can you suggest me a languages that supports this functionality? How's python? – Gijo Varghese Apr 23 '16 at 12:33
0

Here's some example pthreads code, for PHP 7 (pthreads v3+):

<?php
class Filter extends Threaded {

    public function __construct(string $img, array $filters = [], string $out) {
        $this->img = $img;
        $this->filters = $filters;
        $this->out = $out;
    }

    public function run() {
        $image = imagecreatefromjpeg($this->img);

        if (!is_resource($image)) {
            throw new \RuntimeException(
                sprintf(
                    "could not create image resource from %s", $this->img));
        }

        foreach ($this->filters as $filter) {
            imagefilter($image, ...$filter);
        }

        imagejpeg($image, 
            sprintf("%s/%s", 
                $this->out, basename($this->img)));
        imagedestroy($image);
    }

    private $img;
    private $filters;
    private $out;
}

$pool = new Pool(16);

foreach (glob("/path/to/*.JPG") as $image) {
    $pool->submit(new Filter(
        $image, [
            [IMG_FILTER_GRAYSCALE],
            [IMG_FILTER_COLORIZE, 100, 50, 0]
        ],
        "/tmp/dump"));
}

$pool->shutdown();
?>

This uses a Pool of 16 threads to create sepia versions of all the images glob'd.

Joe Watkins
  • 17,032
  • 5
  • 41
  • 62