domingo, 15 de enero de 2012

Smushit plugin en PHP

No hace mucho hable de la novedosa API que nos presentaba Smushit. Bien pues hoy voy a publicar como aprovechar eso para aplicarlo de forma automática en nuestro sitio web.

Para empezar creamos un class.smushit.php con el siguiente código

<?PHP
    // smushit-php - a PHP client for Yahoo!'s Smush.it web service
    //
    // Janu 15, 2012
    // Endika Iglesias <endika2@gmail.com>
    // June 24, 2010
    // Tyler Hall <tylerhall@gmail.com>
class SmushIt{
const SMUSH_URL = 'http://www.smushit.com/ysmush.it/ws.php?';
public $filename;
public $url;
public $compressedUrl;
public $size;
public $compressedSize;
public $savings;
public $error;
public function __construct($data = null){
if(!is_null($data)){
if(preg_match('/https?:\/\//', $data) == 1)
$this->smushURL($data);
else
$this->smushFile($data);
}
}
public function smushURL($url){
$this->url = $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SMUSH_URL . 'img=' . $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$json_str = curl_exec($ch);
curl_close($ch);
return $this->parseResponse($json_str);}
public function smushFile($filename){
$this->filename = $filename;
if(!is_readable($filename)){
$this->error = 'Could not read file';
return false;}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::SMUSH_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('files' => '@' . $filename));
$json_str = curl_exec($ch);
curl_close($ch);
return $this->parseResponse($json_str);}
private function parseResponse($json_str){
            $this->error = null;
            $json = json_decode($json_str);
            if(is_null($json)){
                $this->error = 'Bad response from Smush.it web service';
                return false;
            }
            if(isset($json->error)){
                $this->error = $json->error;
                return false;
            }
            $this->filename       = substr (strrchr ($json->src, '/'), 1 );
            $this->size           = $json->src_size;
            $this->compressedUrl  = $json->dest;
            $this->compressedSize = $json->dest_size;
            $this->savings        = $json->percent;
return true;}
function saveImage($path) {
$url=$this->compressedUrl;
$c = curl_init();
          curl_setopt($c,CURLOPT_URL,$url);
          curl_setopt($c,CURLOPT_HEADER,0);
         curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
         $s = curl_exec($c);
         curl_close($c);
         $f = fopen($path, 'wb');
         $z = fwrite($f,$s);
         if ($z != false) return true;
return false;}
}

Esta clase inicialmente fue creada por Tyler Hall el 24 de Junio del 2010 pero la versión que os paso hoy aquí, tiene ciertas modificaciones que creo que nos vendrían muy bien.

Una vez creada la clase comenzamos a usarla. Os paso un ejemplo de como crear un script que optimice nuestra imagen.

<?php
//incluimos nuestra clase
include('class.smushit.php');
//instanciamos la clase con la URL de la foto original
$img = new SmushIt('http://urlImagenOriginal.com/img/fotos/foto1.jpg');
//optenemos la URL de la imagen optimizada
$urlOptiImg=$img->compressedUrl;
/*por último comprobaremos que nos da un resultado, puede darse el caso de que la imagen no se pueda optimizar más, por tanto la variable $urlOptiImg no devolverá nada*/

 if (isset($urlOptiImg)){
//en caso contrarío almacenaremos la imagen optimizada en la ruta con el nombre que le indiquemos.
     $guardar = $img->saveImage('../../directorio/fotos/imagenOptimizada.jpg');
     var_dump($guardar);
}

?>

Eso es todo :)

No hay comentarios:

Publicar un comentario