Skip to content

Instantly share code, notes, and snippets.

@wilr
Created April 4, 2012 05:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilr/2298046 to your computer and use it in GitHub Desktop.
Save wilr/2298046 to your computer and use it in GitHub Desktop.
An extension for resampling SilverStripe images on upload.
<?php
/**
* An extension to SilverStripes inbuilt {@link Image} class to handle resizing
* large images on upload either through the backend interface or through upload
* forms.
*
* File is resized to a copy, then the original is deleted and the smaller image
* moved back.
*
* Usage:
* <code>
* DataObject::add_extension('Image', 'ResampleUpload');
* </code>
*
* Options:
* Configure the max size using either statics or through instance level
* variables. Note that if using instance level then it won't apply on things
* like admin panels.
*
* <code>
* ResampleUpload::$default_max_x = 45;
* ResampleUpload::$default_max_y = 100;
* </code>
*
*
* @todo provide options to archive large images
*
* @author Will Rossiter <will@fullscreen.io>
* @license http://sam.zoy.org/wtfpl/
*/
class ResampleUpload extends DataObjectDecorator {
static $default_max_x = 1024;
static $default_max_y = 1024;
private $maxX, $maxY;
function setMaxX($x) {
$this->maxX = $x;
}
function setMaxY($y) {
$this->maxY = $y;
}
function getMaxX() {
return ($this->maxX) ? $this->maxX : self::$default_max_x;
}
function getMaxY() {
return ($this->maxY) ? $this->maxY : self::$default_max_y;
}
function onAfterUpload() {
$this->ensureFileIsSmall();
}
function onAfterWrite() {
$this->ensureFileIsSmall();
}
function ensureFileIsSmall() {
$extension = strtolower($this->owner->getExtension());
if($this->owner->getHeight() > $this->getMaxX() || $this->owner->getWidth() > $this->getMaxY()) {
$original = $this->owner->getFullPath();
$resampled = $original. '.tmp.'. $extension;
$gd = new GD($original);
if($gd->hasGD()) {
$gd = $gd->resizeRatio($this->getMaxX(), $this->getMaxY());
if($gd) {
$gd->writeTo($resampled);
unlink($original);
rename($resampled, $original);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment