Archive for the ‘computer tips’ Category

Get First Google Image Search Result with PHP

Saturday, August 13th, 2011

Here’s a quick  & dirty way to get the thumbnail image for the first search result in Google Image Search:

<?php
if(isset($_GET['q'])){
 $q = urlencode($_GET['q']);
 $jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q;
 $result = json_decode(file_get_contents($jsonurl), true);
 header("Content-Type: image/jpg");
 $img = imagecreatefromjpeg($result['responseData']['results'][0]['tbUrl']);
 imagejpeg($img);
 imagedestroy($img);
 
exit;
}
?>
<html>
<body>
<form action='' method='post'>
<fieldset>
<input type='text' name='q' /><input type='submit' name='submit' />
</fieldset>
</form>
<?php
if(isset($_POST['q'])){
 $q = urlencode($_POST['q']);
 $jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q;
 $result = json_decode(file_get_contents($jsonurl), true);
 echo "<img src='{$result['responseData']['results'][0]['tbUrl']}' />";
}
?>
</body>
</html>

A few notes:

  • Your PHP install must have gd which it probably will if you’re running 5+ which is required for json_decode (the function file_get_contents is 5.2+, but is just a shorthand function.)
  • For my purposes I only needed a thumbnail-sized image, but Google’s API provides piles of useful data. View the data directly [example], and copy+paste into a parser [example] if you need help navigating the data structure they provide. PHP’s json_decode will turn Google’s JSON data object into a deeply-nested array (and using “true” for the optional second parameter will make it an associative array which is helpful.
  • When you access the script by URL with the 'q' variable set the image itself will be served, which I needed for my pipeline. This way I was able to call the script in the HTML itself via:
    • <img src='firstgoogleimage.php?q=figgalicous' /> which as of this writing serves:
      Mike Figueroa figgalicous

Clearing Windows 7 Print Spool

Wednesday, June 1st, 2011

Windows 7 and my inkjet printer don’t always get along. When they start giving each other the silent “treatment”, I’m occasionally forced to restart my computer so I can print documents.

I cobbled this batch file together from various sources online. It works about half the time.

@echo off
echo Stopping print spooler.
echo.
net stop spooler
echo Erasing Temporary Junk Printer Documents
echo.
del /Q /F /S %systemroot%\System32\Spool\Printers\*.*
echo Starting print spooler.
echo.
net start spooler

If you’ve never made a batch file, copy the code above into a plain text editor and save the file to your Windows folder with the extension .bat

To use, call the file from the Run… command in the Windows menu.