What I'm trying to do is grab image from clipboard and save it to an image file by using PHP, unfortunately, PHP can not do this, so I install pngpaste on my Mac and use php function shell_exec()
/exec()
/popen()
to execute pngpaste
command to do this job.
First, I install pngpaste
on my Mac:
brew install pngpaste
Then I try to copy an image or take a screenshot to the clipboard, after that I run the following command:
pngpaste ./screenshot.png
it works fine! The screenshot.png
successfully generate.
Then, I try to copy some plaintext to the clipboard(which means there is no image in the clipboard anymore), and run the command above again, it return as the following picture shows (which is an correct output cause there is no image in the clipboard):
Then I try to execute the above command by PHP,I create index.php
, the code inside index.php
is pretty simple:
<?php
$command = '/usr/local/bin/pngpaste ./screenshot.png';
$output = shell_exec($command);
echo $output;
Then I run:
php index.php
It works fine too, if I take a screenshot to the clipboard, screenshot.png
will be created too, and if there is no image in the clipboard, it returns exactly the some words as running command directly.
Everything looks good, now I'm going to use Alfred
. I created a workflow:
Then double click Run Script
and put the command into the box→click save
:
As you can see, I set the workflow Shortcut to control+command+v
, which means when I press control+command+v
, the following command will be executed by Alfred:
/usr/local/bin/php /Users/bruce/Downloads/index.php
Then I take a screenshot to the clipboard and press shortcut control+command+v
, guess what happen? Right! The screenshot.png
is created again, it works fine too.
And then I try to press control+command+v
when there is no image in the clipboard, it should be return pngpaste: No image data found on the clipboard, or could not convert!
right? But guess what, nothing at all, I can't get the $output
returned by shell_exec()
, after this, I tried exec()
/popen()
, but it's the same, no output at all.
I tried to edit the code like this and press shortcut control+command+v
:
<?php
$command = '/usr/local/bin/pngpaste ./screenshot.jpeg';
$output = shell_exec($command);
$output = 'this is a test ouput' . output;
echo $output;
Alfred returned this is a test ouput
, which means the variable $output
is NULL
or empty string
, but it should not be empty, it should be return pngpaste: No image data found on the clipboard, or could not convert!
when there is no image in the clipboard.
So, my question is: How can I solve this issue? How can I get the output that returns by pngpaste
when there is no image in the clipboard?