]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/imagefile.php
Dynamically generate thumbnails (see full text)
[quix0rs-gnu-social.git] / lib / imagefile.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstraction for an image file
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Image
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Zach Copley <zach@status.net>
26  * @copyright 2008-2009 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('GNUSOCIAL')) { exit(1); }
32
33 /**
34  * A wrapper on uploaded files
35  *
36  * Makes it slightly easier to accept an image file from upload.
37  *
38  * @category Image
39  * @package  StatusNet
40  * @author   Evan Prodromou <evan@status.net>
41  * @author   Zach Copley <zach@status.net>
42  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
43  * @link     http://status.net/
44  */
45
46 class ImageFile
47 {
48     var $id;
49     var $filepath;
50     var $barename;
51     var $type;
52     var $height;
53     var $width;
54
55     function __construct($id=null, $filepath=null, $type=null, $width=null, $height=null)
56     {
57         $this->id = $id;
58         $this->filepath = $filepath;
59
60         $info = @getimagesize($this->filepath);
61
62         if (!(
63             ($info[2] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) ||
64             ($info[2] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) ||
65             $info[2] == IMAGETYPE_BMP ||
66             ($info[2] == IMAGETYPE_WBMP && function_exists('imagecreatefromwbmp')) ||
67             ($info[2] == IMAGETYPE_XBM && function_exists('imagecreatefromxbm')) ||
68             ($info[2] == IMAGETYPE_PNG && function_exists('imagecreatefrompng')))) {
69
70             // TRANS: Exception thrown when trying to upload an unsupported image file format.
71             throw new UnsupportedMediaException(_('Unsupported image format.'), $this->filepath);
72         }
73
74         $this->type = ($info) ? $info[2]:$type;
75         $this->width = ($info) ? $info[0]:$width;
76         $this->height = ($info) ? $info[1]:$height;
77     }
78
79     public function getPath()
80     {
81         if (!file_exists($this->filepath)) {
82             throw new ServerException('No file in ImageFile filepath');
83         }
84
85         return $this->filepath;
86     }
87
88     static function fromUpload($param='upload')
89     {
90         switch ($_FILES[$param]['error']) {
91          case UPLOAD_ERR_OK: // success, jump out
92             break;
93
94          case UPLOAD_ERR_INI_SIZE:
95          case UPLOAD_ERR_FORM_SIZE:
96             // TRANS: Exception thrown when too large a file is uploaded.
97             // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
98             throw new Exception(sprintf(_('That file is too big. The maximum file size is %s.'), ImageFile::maxFileSize()));
99
100          case UPLOAD_ERR_PARTIAL:
101             @unlink($_FILES[$param]['tmp_name']);
102             // TRANS: Exception thrown when uploading an image and that action could not be completed.
103             throw new Exception(_('Partial upload.'));
104
105          case UPLOAD_ERR_NO_FILE:
106             // No file; probably just a non-AJAX submission.
107          default:
108             common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " . $_FILES[$param]['error']);
109             // TRANS: Exception thrown when uploading an image fails for an unknown reason.
110             throw new Exception(_('System error uploading file.'));
111         }
112
113         $info = @getimagesize($_FILES[$param]['tmp_name']);
114
115         if (!$info) {
116             @unlink($_FILES[$param]['tmp_name']);
117             // TRANS: Exception thrown when uploading a file as image that is not an image or is a corrupt file.
118             throw new UnsupportedMediaException(_('Not an image or corrupt file.'), '[deleted]');
119         }
120
121         return new ImageFile(null, $_FILES[$param]['tmp_name']);
122     }
123
124     /**
125      * Compat interface for old code generating avatar thumbnails...
126      * Saves the scaled file directly into the avatar area.
127      *
128      * @param int $size target width & height -- must be square
129      * @param int $x (default 0) upper-left corner to crop from
130      * @param int $y (default 0) upper-left corner to crop from
131      * @param int $w (default full) width of image area to crop
132      * @param int $h (default full) height of image area to crop
133      * @return string filename
134      */
135     function resize($size, $x = 0, $y = 0, $w = null, $h = null)
136     {
137         $targetType = $this->preferredType();
138         $outname = Avatar::filename($this->id,
139                                     image_type_to_extension($targetType),
140                                     $size,
141                                     common_timestamp());
142         $outpath = Avatar::path($outname);
143         $this->resizeTo($outpath, $size, $size, $x, $y, $w, $h);
144         return $outname;
145     }
146
147     /**
148      * Copy the image file to the given destination.
149      * For obscure formats, this will automatically convert to PNG;
150      * otherwise the original file will be copied as-is.
151      *
152      * @param string $outpath
153      * @return string filename
154      */
155     function copyTo($outpath)
156     {
157         return $this->resizeTo($outpath, $this->width, $this->height);
158     }
159
160     /**
161      * Create and save a thumbnail image.
162      *
163      * @param string $outpath
164      * @param int $width target width
165      * @param int $height target height
166      * @param int $x (default 0) upper-left corner to crop from
167      * @param int $y (default 0) upper-left corner to crop from
168      * @param int $w (default full) width of image area to crop
169      * @param int $h (default full) height of image area to crop
170      * @return string full local filesystem filename
171      */
172     function resizeTo($outpath, $width, $height, $x=0, $y=0, $w=null, $h=null)
173     {
174         $w = ($w === null) ? $this->width:$w;
175         $h = ($h === null) ? $this->height:$h;
176         $targetType = $this->preferredType();
177
178         if (!file_exists($this->filepath)) {
179             // TRANS: Exception thrown during resize when image has been registered as present, but is no longer there.
180             throw new Exception(_('Lost our file.'));
181         }
182
183         // Don't crop/scale if it isn't necessary
184         if ($width === $this->width
185             && $height === $this->height
186             && $x === 0
187             && $y === 0
188             && $w === $this->width
189             && $h === $this->height
190             && $this->type == $targetType) {
191
192             @copy($this->filepath, $outpath);
193             return $outpath;
194         }
195
196         switch ($this->type) {
197          case IMAGETYPE_GIF:
198             $image_src = imagecreatefromgif($this->filepath);
199             break;
200          case IMAGETYPE_JPEG:
201             $image_src = imagecreatefromjpeg($this->filepath);
202             break;
203          case IMAGETYPE_PNG:
204             $image_src = imagecreatefrompng($this->filepath);
205             break;
206          case IMAGETYPE_BMP:
207             $image_src = imagecreatefrombmp($this->filepath);
208             break;
209          case IMAGETYPE_WBMP:
210             $image_src = imagecreatefromwbmp($this->filepath);
211             break;
212          case IMAGETYPE_XBM:
213             $image_src = imagecreatefromxbm($this->filepath);
214             break;
215          default:
216             // TRANS: Exception thrown when trying to resize an unknown file type.
217             throw new Exception(_('Unknown file type'));
218         }
219
220         $image_dest = imagecreatetruecolor($width, $height);
221
222         if ($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG || $this->type == IMAGETYPE_BMP) {
223
224             $transparent_idx = imagecolortransparent($image_src);
225
226             if ($transparent_idx >= 0) {
227
228                 $transparent_color = imagecolorsforindex($image_src, $transparent_idx);
229                 $transparent_idx = imagecolorallocate($image_dest, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
230                 imagefill($image_dest, 0, 0, $transparent_idx);
231                 imagecolortransparent($image_dest, $transparent_idx);
232
233             } elseif ($this->type == IMAGETYPE_PNG) {
234
235                 imagealphablending($image_dest, false);
236                 $transparent = imagecolorallocatealpha($image_dest, 0, 0, 0, 127);
237                 imagefill($image_dest, 0, 0, $transparent);
238                 imagesavealpha($image_dest, true);
239
240             }
241         }
242
243         imagecopyresampled($image_dest, $image_src, 0, 0, $x, $y, $width, $height, $w, $h);
244
245         switch ($targetType) {
246          case IMAGETYPE_GIF:
247             imagegif($image_dest, $outpath);
248             break;
249          case IMAGETYPE_JPEG:
250             imagejpeg($image_dest, $outpath, common_config('image', 'jpegquality'));
251             break;
252          case IMAGETYPE_PNG:
253             imagepng($image_dest, $outpath);
254             break;
255          default:
256             // TRANS: Exception thrown when trying resize an unknown file type.
257             throw new Exception(_('Unknown file type'));
258         }
259
260         imagedestroy($image_src);
261         imagedestroy($image_dest);
262
263         return $outpath;
264     }
265
266     /**
267      * Several obscure file types should be normalized to PNG on resize.
268      *
269      * @fixme consider flattening anything not GIF or JPEG to PNG
270      * @return int
271      */
272     function preferredType()
273     {
274         if($this->type == IMAGETYPE_BMP) {
275             //we don't want to save BMP... it's an inefficient, rare, antiquated format
276             //save png instead
277             return IMAGETYPE_PNG;
278         } else if($this->type == IMAGETYPE_WBMP) {
279             //we don't want to save WBMP... it's a rare format that we can't guarantee clients will support
280             //save png instead
281             return IMAGETYPE_PNG;
282         } else if($this->type == IMAGETYPE_XBM) {
283             //we don't want to save XBM... it's a rare format that we can't guarantee clients will support
284             //save png instead
285             return IMAGETYPE_PNG;
286         }
287         return $this->type;
288     }
289
290     function unlink()
291     {
292         @unlink($this->filepath);
293     }
294
295     static function maxFileSize()
296     {
297         $value = ImageFile::maxFileSizeInt();
298
299         if ($value > 1024 * 1024) {
300             $value = $value/(1024*1024);
301             // TRANS: Number of megabytes. %d is the number.
302             return sprintf(_m('%dMB','%dMB',$value),$value);
303         } else if ($value > 1024) {
304             $value = $value/1024;
305             // TRANS: Number of kilobytes. %d is the number.
306             return sprintf(_m('%dkB','%dkB',$value),$value);
307         } else {
308             // TRANS: Number of bytes. %d is the number.
309             return sprintf(_m('%dB','%dB',$value),$value);
310         }
311     }
312
313     static function maxFileSizeInt()
314     {
315         return min(ImageFile::strToInt(ini_get('post_max_size')),
316                    ImageFile::strToInt(ini_get('upload_max_filesize')),
317                    ImageFile::strToInt(ini_get('memory_limit')));
318     }
319
320     static function strToInt($str)
321     {
322         $unit = substr($str, -1);
323         $num = substr($str, 0, -1);
324
325         switch(strtoupper($unit)){
326          case 'G':
327             $num *= 1024;
328          case 'M':
329             $num *= 1024;
330          case 'K':
331             $num *= 1024;
332         }
333
334         return $num;
335     }
336
337     public function scaleToFit($maxWidth=null, $maxHeight=null, $crop=null)
338     {
339         return self::getScalingValues($this->width, $this->height,
340                                         $maxWidth, $maxHeight, $crop);
341     }
342
343     /*
344      * Gets scaling values for images of various types. Cropping can be enabled.
345      *
346      * Values will scale _up_ to fit max values if cropping is enabled!
347      * With cropping disabled, the max value of each axis will be respected.
348      *
349      * @param $width    int Original width
350      * @param $height   int Original height
351      * @param $maxW     int Resulting max width
352      * @param $maxH     int Resulting max height
353      * @param $crop     int Crop to the size (not preserving aspect ratio)
354      */
355     public static function getScalingValues($width, $height,
356                                         $maxW=null, $maxH=null,
357                                         $crop=null)
358     {
359         $maxW = $maxW ?: common_config('thumbnail', 'width');
360         $maxH = $maxH ?: common_config('thumbnail', 'height');
361   
362         if ($maxW < 1 || ($maxH !== null && $maxH < 1)) {
363             throw new ServerException('Bad parameters for ImageFile::getScalingValues');
364         } elseif ($maxH === null) {
365             // if maxH is null, we set maxH to equal maxW and enable crop
366             $maxH = $maxW;
367             $crop = true;
368         }
369   
370         // Cropping data (for original image size). Default values, 0 and null,
371         // imply no cropping and with preserved aspect ratio (per axis).
372         $cx = 0;    // crop x
373         $cy = 0;    // crop y
374         $cw = null; // crop area width
375         $ch = null; // crop area height
376   
377         if ($crop) {
378             $s_ar = $width / $height;
379             $t_ar = $maxW / $maxH;
380
381             $rw = $maxW;
382             $rh = $maxH;
383
384             // Source aspect ratio differs from target, recalculate crop points!
385             if ($s_ar > $t_ar) {
386                 $cx = floor($width / 2 - $height * $t_ar / 2);
387                 $cw = ceil($height * $t_ar);
388             } elseif ($s_ar < $t_ar) {
389                 $cy = floor($height / 2 - $width / $t_ar / 2);
390                 $ch = ceil($width / $t_ar);
391             }
392         } else {
393             $rw = $maxW;
394             $rh = ceil($height * $rw / $width);
395
396             // Scaling caused too large height, decrease to max accepted value
397             if ($rh > $maxH) {
398                 $rh = $maxH;
399                 $rw = ceil($width * $rh / $height);
400             }
401         }
402         return array(intval($rw), intval($rh),
403                     intval($cx), intval($cy),
404                     is_null($cw) ? null : intval($cw),
405                     is_null($ch) ? null : intval($ch));
406     }
407 }
408
409 //PHP doesn't (as of 2/24/2010) have an imagecreatefrombmp so conditionally define one
410 if(!function_exists('imagecreatefrombmp')){
411     //taken shamelessly from http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
412     function imagecreatefrombmp($p_sFile)
413     {
414         //    Load the image into a string
415         $file    =    fopen($p_sFile,"rb");
416         $read    =    fread($file,10);
417         while(!feof($file)&&($read<>""))
418             $read    .=    fread($file,1024);
419
420         $temp    =    unpack("H*",$read);
421         $hex    =    $temp[1];
422         $header    =    substr($hex,0,108);
423
424         //    Process the header
425         //    Structure: http://www.fastgraph.com/help/bmp_header_format.html
426         if (substr($header,0,4)=="424d")
427         {
428             //    Cut it in parts of 2 bytes
429             $header_parts    =    str_split($header,2);
430
431             //    Get the width        4 bytes
432             $width            =    hexdec($header_parts[19].$header_parts[18]);
433
434             //    Get the height        4 bytes
435             $height            =    hexdec($header_parts[23].$header_parts[22]);
436
437             //    Unset the header params
438             unset($header_parts);
439         }
440
441         //    Define starting X and Y
442         $x                =    0;
443         $y                =    1;
444
445         //    Create newimage
446         $image            =    imagecreatetruecolor($width,$height);
447
448         //    Grab the body from the image
449         $body            =    substr($hex,108);
450
451         //    Calculate if padding at the end-line is needed
452         //    Divided by two to keep overview.
453         //    1 byte = 2 HEX-chars
454         $body_size        =    (strlen($body)/2);
455         $header_size    =    ($width*$height);
456
457         //    Use end-line padding? Only when needed
458         $usePadding        =    ($body_size>($header_size*3)+4);
459
460         //    Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
461         //    Calculate the next DWORD-position in the body
462         for ($i=0;$i<$body_size;$i+=3)
463         {
464             //    Calculate line-ending and padding
465             if ($x>=$width)
466             {
467                 //    If padding needed, ignore image-padding
468                 //    Shift i to the ending of the current 32-bit-block
469                 if ($usePadding)
470                     $i    +=    $width%4;
471
472                 //    Reset horizontal position
473                 $x    =    0;
474
475                 //    Raise the height-position (bottom-up)
476                 $y++;
477
478                 //    Reached the image-height? Break the for-loop
479                 if ($y>$height)
480                     break;
481             }
482
483             //    Calculation of the RGB-pixel (defined as BGR in image-data)
484             //    Define $i_pos as absolute position in the body
485             $i_pos    =    $i*2;
486             $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]);
487             $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]);
488             $b        =    hexdec($body[$i_pos].$body[$i_pos+1]);
489
490             //    Calculate and draw the pixel
491             $color    =    imagecolorallocate($image,$r,$g,$b);
492             imagesetpixel($image,$x,$height-$y,$color);
493
494             //    Raise the horizontal position
495             $x++;
496         }
497
498         //    Unset the body / free the memory
499         unset($body);
500
501         //    Return image-object
502         return $image;
503     }
504 }   // if(!function_exists('imagecreatefrombmp'))