<?php
/*
@version 1.0
@autor : jpmaster.net@gmail.com
*/
class jpImage{
var $imageDefault = "";
var $searchDefault = "jpmaster";
var $options = array();
var $widthDefault = 50; //ancho por defecto
var $heightDefault = 50; //alto por defecto
var $url_service = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s+photo&imgsz=small|medium&as_filetype=jpg";
function __construct($option){
$this->options = $option;
$fuente = $this->leer_datos(sprintf($this->url_service, $this->options['query']));
$json = json_decode($fuente);
$imgurl = empty($json->responseData->results[0]->unescapedUrl) ? $this->imageDefault : $json->responseData->results[0]->unescapedUrl;
$width = empty($this->options['width']) ? $this->widthDefault : $this->options['width'];
$height = empty($this->options['height']) ? $this->heightDefault : $this->options['height'];
//results
$result = @getimagesize($imgurl);
if(!$result) die('Imagen no existe '.$imgurl);
switch ($result['mime']) {
case 'image/jpeg':
header(sprintf("Content-type: %s", $result['mime']));
$img = @imagecreatefromjpeg($imgurl);
$thumb = $this->resizeFit($img, $width, $height);
imagejpeg($thumb);
imagedestroy($thumb);
break;
default:
echo 'error xD';
break;
}
}
private function resizeFit($im, $width, $height){
$ow = imagesx($im); $oh = imagesy($im);
if($width/$ow > $height/$oh) {
$nw = $width;
$nh = ($oh * $nw) / $ow;
$px = 0;
$py = ($height - $nh) / 2;
} else {
$nh = $height;
$nw = ($ow * $nh) / $oh;
$py = 0;
$px = ($width - $nw) / 2;
}
$new = imagecreatetruecolor($width,$height);
imagecopyresampled($new, $im, $px, $py, 0, 0, $nw, $nh, $ow, $oh);
return $new;
}
private function leer_datos($url){
return file_get_contents($url); //si deseas puedes usar curl
}
}