Reputation: 11780
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
}
?>
Upvotes: 0
Views: 2123
Reputation: 17168
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.
Upvotes: 0
Reputation: 36
you can user pcntl_fork() function, but it creates new process. PHP is not best choice, if you want to code multithreading programs.
Upvotes: 1