Skip to content

Instantly share code, notes, and snippets.

@SeanJA
Created November 19, 2010 05:04
Show Gist options
  • Select an option

  • Save SeanJA/706140 to your computer and use it in GitHub Desktop.

Select an option

Save SeanJA/706140 to your computer and use it in GitHub Desktop.
Compress images
<?php
$s = new smushit();
$smushed = $s->compress('http://thechronicleherald.ca/sites/default/files/imagecache/story_thumb/stories/photos/11-18-10_cl111710auditor2_1.jpg');
print_r($smushed);
<?php
/**
* Just a dummy class so you know what you get back from the smushit compress function
*/
abstract class smushed {
/**
* The url of the source image
* @var string
*/
public $src;
/**
* The size of the file in bytes
* @var int
*/
public $src_size;
/**
* The url of the smushed image
* @var string
*/
public $dest;
/**
* The size of the smushed file in bytes
* @var int
*/
public $dest_size;
/**
* The amount of compression
* @var float
*/
public $percent;
/**
* Not sure...
* @var presumably an integer...?
*/
public $id;
}
<?php
/**
* Custom exception handler
*/
class Smush_exception extends Exception {
/**
* Path to image
* @var string $image
*/
private $image = '';
/**
* Overload the exception construct so we can provide an image name
* @param string $message
* @param string $image
*/
public function __construct($message, $image) {
$this->image = $image;
parent::__construct($message);
}
// Return image path.
final function getImage() {
return $this->image;
}
}
<?php
/**
* Description: Compresses images using Smush.it
*
* @license MIT
* @author Mathew Davies <thepixeldeveloper@googlemail.com>
*/
class smushit {
const user_agent = 'Smush.it PHP Class (+http://mathew-davies.co.uk)';
private $curl = NULL;
/**
* Smush.it request URL
*/
const url = 'http://www.smushit.com/ysmush.it/ws.php';
/**
* Make sure any prerequisite are installed.
*/
public function __construct() {
if (!extension_loaded('json')) {
throw new RuntimeException('The json extension was not found');
}
if (!extension_loaded('curl')) {
throw new RuntimeException('The cURL extension was not found.');
}
// cURL handler
$this->curl = curl_init();
// Return HTTP response
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, TRUE);
}
/**
* Compress image using smush.it. Image must be available online
*
* @param string url to image.
* @throws Smush_exception
* @return smushed
*/
public function compress($image) {
// Set appropriate URL.
curl_setopt($this->curl, CURLOPT_URL, self::url . '?' . http_build_query(array('img' => $image)));
// Set user agent
curl_setopt($this->curl, CURLOPT_USERAGENT, self::user_agent);
// Execute the HTTP request
$request = curl_exec($this->curl);
// JSON response
$result = json_decode($request);
if (isset($result->error)) {
throw new Smush_exception($result->error, $image);
}
$result->dest = urldecode($result->dest);
// Return response data
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment