summaryrefslogtreecommitdiff
path: root/program/include/rcube_image.php
blob: 80e8bd4f3815bcd6580b7d3eb56774879fb4a38d (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php

/*
 +-----------------------------------------------------------------------+
 | program/include/rcube_image.php                                       |
 |                                                                       |
 | This file is part of the Roundcube Webmail client                     |
 | Copyright (C) 2005-2012, The Roundcube Dev Team                       |
 | Copyright (C) 2011-2012, Kolab Systems AG                             |
 |                                                                       |
 | Licensed under the GNU General Public License version 3 or            |
 | any later version with exceptions for skins & plugins.                |
 | See the README file for a full license statement.                     |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Image resizer and converter                                         |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
 | Author: Aleksander Machniak <alec@alec.pl>                            |
 +-----------------------------------------------------------------------+
*/

class rcube_image
{
    private $image_file;

    const TYPE_GIF = 1;
    const TYPE_JPG = 2;
    const TYPE_PNG = 3;
    const TYPE_TIF = 4;

    public static $extensions = array(
        self::TYPE_GIF => 'gif',
        self::TYPE_JPG => 'jpg',
        self::TYPE_PNG => 'png',
        self::TYPE_TIF => 'tif',
    );


    function __construct($filename)
    {
        $this->image_file = $filename;
    }

    /**
     * Get image properties.
     *
     * @return mixed Hash array with image props like type, width, height
     */
    public function props()
    {
        // use GD extension
        if (function_exists('getimagesize') && ($imsize = @getimagesize($this->image_file))) {
            $width   = $imsize[0];
            $height  = $imsize[1];
            $gd_type = $imsize['2'];
            $type    = image_type_to_extension($imsize['2'], false);
        }

        // use ImageMagick
        if (!$type && ($data = $this->identify())) {
            list($type, $width, $height) = $data;
        }

        if ($type) {
            return array(
                'type'    => $type,
                'gd_type' => $gd_type,
                'width'   => $width,
                'height'  => $height,
            );
        }
    }

    /**
     * Resize image to a given size
     *
     * @param int    $size      Max width/height size
     * @param string $filename  Output filename
     *
     * @return bool True on success, False on failure
     */
    public function resize($size, $filename = null)
    {
        $result  = false;
        $rcube   = rcube::get_instance();
        $convert = $rcube->config->get('im_convert_path', false);
        $props   = $this->props();

        if (!$filename) {
            $filename = $this->image_file;
        }

        // use Imagemagick
        if ($convert) {
            $p['out']  = $filename;
            $p['in']   = $this->image_file;
            $p['size'] = $size.'x'.$size;
            $type      = $props['type'];

            if (!$type && ($data = $this->identify())) {
                $type = $data[0];
            }

            $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
            $p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
            $p['-opts'] = array('-resize' => $size.'>');

            if (in_array($type, explode(',', $p['types']))) { // Valid type?
                $result = rcube::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p);
            }

            if ($result === '') {
                return true;
            }
        }

        // use GD extension
        $gd_types = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG);
        if ($props['gd_type'] && in_array($props['gd_type'], $gd_types)) {
            if ($props['gd_type'] == IMAGETYPE_JPEG) {
                $image = imagecreatefromjpeg($this->image_file);
            }
            elseif($props['gd_type'] == IMAGETYPE_GIF) {
                $image = imagecreatefromgif($this->image_file);
            }
            elseif($props['gd_type'] == IMAGETYPE_PNG) {
                $image = imagecreatefrompng($this->image_file);
            }

            $scale  = $size / max($props['width'], $props['height']);
            $width  = $props['width']  * $scale;
            $height = $props['height'] * $scale;

            $new_image = imagecreatetruecolor($width, $height);

            // Fix transparency of gif/png image
            if ($props['gd_type'] != IMAGETYPE_JPEG) {
                imagealphablending($new_image, false);
                imagesavealpha($new_image, true);
                $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
                imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);
            }

            imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $props['width'], $props['height']);
            $image = $new_image;

            if ($props['gd_type'] == IMAGETYPE_JPEG) {
                $result = imagejpeg($image, $filename, 75);
            }
            elseif($props['gd_type'] == IMAGETYPE_GIF) {
                $result = imagegif($image, $filename);
            }
            elseif($props['gd_type'] == IMAGETYPE_PNG) {
                $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
            }

            if ($result) {
                return true;
            }
        }

        // @TODO: print error to the log?
        return false;
    }

    /**
     * Convert image to a given type
     *
     * @param int    $type      Destination file type (see class constants)
     * @param string $filename  Output filename (if empty, original file will be used
     *                          and filename extension will be modified)
     *
     * @return bool True on success, False on failure
     */
    public function convert($type, $filename = null)
    {
        $rcube   = rcube::get_instance();
        $convert = $rcube->config->get('im_convert_path', false);

        if (!$filename) {
            $filename = $this->image_file;

            // modify extension
            if ($extension = self::$extensions[$type]) {
                $filename = preg_replace('/\.[^.]+$/', '', $filename) . '.' . $extension;
            }
        }

        // use ImageMagick
        if ($convert) {
            $p['in']   = $this->image_file;
            $p['out']  = $filename;
            $p['type'] = self::$extensions[$type];

            $result = rcube::exec($convert . ' 2>&1 -colorspace RGB -quality 75 {in} {type}:{out}', $p);

            if ($result === '') {
                return true;
            }
        }

        // use GD extension (TIFF isn't supported)
        $props    = $this->props();
        $gd_types = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG);

        if ($props['gd_type'] && in_array($props['gd_type'], $gd_types)) {
            if ($props['gd_type'] == IMAGETYPE_JPEG) {
                $image = imagecreatefromjpeg($this->image_file);
            }
            else if ($props['gd_type'] == IMAGETYPE_GIF) {
                $image = imagecreatefromgif($this->image_file);
            }
            else if ($props['gd_type'] == IMAGETYPE_PNG) {
                $image = imagecreatefrompng($this->image_file);
            }

            if ($type == self::TYPE_JPG) {
                $result = imagejpeg($image, $filename, 75);
            }
            else if ($type == self::TYPE_GIF) {
                $result = imagegif($image, $filename);
            }
            else if ($type == self::TYPE_PNG) {
                $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
            }
        }

        // @TODO: print error to the log?
        return false;
    }

    /**
     * Identify command handler.
     */
    private function identify()
    {
        $rcube = rcube::get_instance();

        if ($cmd = $rcube->config->get('im_identify_path')) {
            $args = array('in' => $this->image_file, 'format' => "%m %[fx:w] %[fx:h]");
            $id   = rcube::exec($cmd. ' 2>/dev/null -format {format} {in}', $args);

            if ($id) {
                return explode(' ', strtolower($id));
            }
        }
    }

}