1 <?php
2
3 4 5 6 7
8
9 class ImageAutoResize extends DataObjectDecorator {
10
11 private static $quality = 90;
12 private static $maxWidth = 1000;
13 private static $maxHeight = 800;
14 private static $disable = false;
15 private static $allowed_types = array(IMAGETYPE_JPEG);
16
17 public static function get_max_size() {
18 return array(
19 'Width' => self::$maxWidth,
20 'Height' => self::$maxHeight
21 );
22 }
23
24 public static function set_max_size($width, $height) {
25 self::$maxWidth = (int) $width;
26 self::$maxHeight = (int) $height;
27 }
28
29 public static function set_quality($val) {
30 self::$quality = (int) $val;
31 }
32
33 public static function quality() {
34 return self::$quality;
35 }
36
37 public static function disable() {
38 self::$disable = true;
39 }
40
41 public static function enable() {
42 self::$disable = false;
43 }
44
45 public static function allowed_types() {
46 return self::$allowed_types;
47 }
48
49 public static function set_allowed_types($value) {
50 return self::$allowed_types = $value;
51 }
52
53 public static function allow_type($value) {
54 return self::$allowed_types[] = $value;
55 }
56
57 function onAfterWrite() {
58 parent::onAfterWrite();
59 $this->doAutoResize();
60 }
61
62 function onAfterUpload() {
63 $this->doAutoResize();
64 }
65
66 function doAutoResize() {
67 if (self::$disable) return false;
68
69 $filename = $this->owner->getFullPath();
70 if (!file_exists($filename)) return false;
71
72 try {
73 list($width, $height, $type ) = @getimagesize($filename);
74 if (!$width) return false;
75 if (array_search($type, self::$allowed_types) === false) return false;
76
77 if ($width > self::$maxWidth || $height > self::$maxHeight) {
78 $gd = new GD($filename);
79 if ($gd->hasGD()) {
80 $gd->setQuality(self::$quality);
81 $gd = $gd->resizeRatio(self::$maxWidth, self::$maxHeight);
82 $gd->writeTo($filename);
83 return true;
84 }
85 }
86 } catch (Exception $e) {
87 return false;
88 }
89 return false;
90 }
91 }
92
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the
Silverstripe Forums to ask development related questions.
-