Skip to content

@wilr /ResampleUpload.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.