public
Last active

An extension for resampling SilverStripe images on upload.

  • Download Gist
ResampleUpload.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
<?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);
}
}
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.