Hello,
I am attempting to use pipes to have ImageMagick rotate an image and return the data to PHP instead of writing over the source file. My key goal is to carry out the rotation operation without using temporary files and without writing over the source file.
Currently, I am able to open a pipe using popen:
$cmd = "mogrify -quality \"100\" -rotate \"90\" \"$path_to_image\"";
$original_handle = popen($cmd, "rb");
while(!feof($original_handle)) {
$buffer = fgets($original_handle, 1024);
$content_original .= $buffer;
}
pclose($original_handle);
This rotates the image and writes over it, and there is no data in $content _original.
According to Image Magick documentation, using - for the source and destination files will cause ImageMagick to read from standard input and write to standard output. So I then tried to use proc_open to carry out the operation. I used the following code:
$original_handle = fopen($path_to__image, "rb");
while(!feof($original_handle)) {
$buffer = fread($original_handle, 1024);
$content_original .= $buffer;
}
fclose($original_handle);
$descriptorspec = array(
0 => array("pipe", "rb"), // stdin is a pipe that the child will read from
1 => array("pipe", "wb"), // stdout is a pipe that the child will write to
2 => array("file", "./tmp/error-output.txt", "a") // stderr is a file to write to
);
$process = proc_open("mogrify -quality \"100\" -rotate \"90\" \"-\" \"-\"", $descriptorspec, $pipes);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
fwrite($pipes[0], $content_original);
fclose($pipes[0]);
while(!feof($pipes[1])) {
$buffer = fgets($pipes[1], 1024);
$content_new .= $buffer;
echo $buffer;
}
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
This will read the binary data from the file, and the proc_open call will return true. However, it does not echo $buffer, and there is nothing in $content_new.
I have found that using the file name in the proc_open as with popen while commenting out the writing to and closing of pipe[0] will result in the image being rotated and written over. Again, it appears no data is returned to PHP from the other pipe.
This is being tested on WinXP/Apache 2/PHP 4.3.2 configuation.
This is my first time to attempt to use pipes, so I'm thinking the problem is due to some oversight on my part. Can anyone help by sharing their knowledge or experience?
Thank you,
Shaun