source: trunk/admin/include/image.class.php @ 13843

Last change on this file since 13843 was 13843, checked in by plg, 12 years ago

feature 2604: support rotation on derivatives

File size: 20.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24// +-----------------------------------------------------------------------+
25// |                           Image Interface                             |
26// +-----------------------------------------------------------------------+
27
28// Define all needed methods for image class
29interface imageInterface
30{
31  function get_width();
32
33  function get_height();
34
35  function set_compression_quality($quality);
36
37  function crop($width, $height, $x, $y);
38
39  function strip();
40
41  function rotate($rotation);
42
43  function resize($width, $height);
44
45  function sharpen($amount);
46
47  function compose($overlay, $x, $y, $opacity);
48
49  function write($destination_filepath);
50}
51
52// +-----------------------------------------------------------------------+
53// |                          Main Image Class                             |
54// +-----------------------------------------------------------------------+
55
56class pwg_image
57{
58  var $image;
59  var $library = '';
60  var $source_filepath = '';
61
62  function __construct($source_filepath, $library=null)
63  {
64    $this->source_filepath = $source_filepath;
65
66    trigger_action('load_image_library', array(&$this) );
67
68    if (is_object($this->image))
69    {
70      return; // A plugin may have load its own library
71    }
72
73    $extension = strtolower(get_extension($source_filepath));
74
75    if (!in_array($extension, array('jpg', 'jpeg', 'png', 'gif')))
76    {
77      die('[Image] unsupported file extension');
78    }
79
80    if (!($this->library = self::get_library($library, $extension)))
81    {
82      die('No image library available on your server.');
83    }
84
85    $class = 'image_'.$this->library;
86    $this->image = new $class($source_filepath);
87  }
88
89  // Unknow methods will be redirected to image object
90  function __call($method, $arguments)
91  {
92    return call_user_func_array(array($this->image, $method), $arguments);
93  }
94
95  // Piwigo resize function
96  function pwg_resize($destination_filepath, $max_width, $max_height, $quality, $automatic_rotation=true, $strip_metadata=false, $crop=false, $follow_orientation=true)
97  {
98    $starttime = get_moment();
99
100    // width/height
101    $source_width  = $this->image->get_width();
102    $source_height = $this->image->get_height();
103
104    $rotation = null;
105    if ($automatic_rotation)
106    {
107      $rotation = self::get_rotation_angle($this->source_filepath);
108    }
109    $resize_dimensions = self::get_resize_dimensions($source_width, $source_height, $max_width, $max_height, $rotation, $crop, $follow_orientation);
110
111    // testing on height is useless in theory: if width is unchanged, there
112    // should be no resize, because width/height ratio is not modified.
113    if ($resize_dimensions['width'] == $source_width and $resize_dimensions['height'] == $source_height)
114    {
115      // the image doesn't need any resize! We just copy it to the destination
116      copy($this->source_filepath, $destination_filepath);
117      return $this->get_resize_result($destination_filepath, $resize_dimensions['width'], $resize_dimensions['height'], $starttime);
118    }
119
120    $this->image->set_compression_quality($quality);
121
122    if ($strip_metadata)
123    {
124      // we save a few kilobytes. For example a thumbnail with metadata weights 25KB, without metadata 7KB.
125      $this->image->strip();
126    }
127
128    if (isset($resize_dimensions['crop']))
129    {
130      $this->image->crop($resize_dimensions['crop']['width'], $resize_dimensions['crop']['height'], $resize_dimensions['crop']['x'], $resize_dimensions['crop']['y']);
131    }
132
133    $this->image->resize($resize_dimensions['width'], $resize_dimensions['height']);
134
135    if (isset($rotation))
136    {
137      $this->image->rotate($rotation);
138    }
139
140    $this->image->write($destination_filepath);
141
142    // everything should be OK if we are here!
143    return $this->get_resize_result($destination_filepath, $resize_dimensions['width'], $resize_dimensions['height'], $starttime);
144  }
145
146  static function get_resize_dimensions($width, $height, $max_width, $max_height, $rotation=null, $crop=false, $follow_orientation=true)
147  {
148    $rotate_for_dimensions = false;
149    if (isset($rotation) and in_array(abs($rotation), array(90, 270)))
150    {
151      $rotate_for_dimensions = true;
152    }
153
154    if ($rotate_for_dimensions)
155    {
156      list($width, $height) = array($height, $width);
157    }
158
159    if ($crop)
160    {
161      $x = 0;
162      $y = 0;
163
164      if ($width < $height and $follow_orientation)
165      {
166        list($max_width, $max_height) = array($max_height, $max_width);
167      }
168
169      $img_ratio = $width / $height;
170      $dest_ratio = $max_width / $max_height;
171
172      if($dest_ratio > $img_ratio)
173      {
174        $destHeight = round($width * $max_height / $max_width);
175        $y = round(($height - $destHeight) / 2 );
176        $height = $destHeight;
177      }
178      elseif ($dest_ratio < $img_ratio)
179      {
180        $destWidth = round($height * $max_width / $max_height);
181        $x = round(($width - $destWidth) / 2 );
182        $width = $destWidth;
183      }
184    }
185
186    $ratio_width  = $width / $max_width;
187    $ratio_height = $height / $max_height;
188    $destination_width = $width;
189    $destination_height = $height;
190
191    // maximal size exceeded ?
192    if ($ratio_width > 1 or $ratio_height > 1)
193    {
194      if ($ratio_width < $ratio_height)
195      {
196        $destination_width = round($width / $ratio_height);
197        $destination_height = $max_height;
198      }
199      else
200      {
201        $destination_width = $max_width;
202        $destination_height = round($height / $ratio_width);
203      }
204    }
205
206    if ($rotate_for_dimensions)
207    {
208      list($destination_width, $destination_height) = array($destination_height, $destination_width);
209    }
210
211    $result = array(
212      'width' => $destination_width,
213      'height'=> $destination_height,
214      );
215
216    if ($crop and ($x or $y))
217    {
218      $result['crop'] = array(
219        'width' => $width,
220        'height' => $height,
221        'x' => $x,
222        'y' => $y,
223        );
224    }
225    return $result;
226  }
227
228  static function get_rotation_angle($source_filepath)
229  {
230    list($width, $height, $type) = getimagesize($source_filepath);
231    if (IMAGETYPE_JPEG != $type)
232    {
233      return null;
234    }
235
236    if (!function_exists('exif_read_data'))
237    {
238      return null;
239    }
240
241    $rotation = 0;
242
243    $exif = exif_read_data($source_filepath);
244
245    if (isset($exif['Orientation']) and preg_match('/^\s*(\d)/', $exif['Orientation'], $matches))
246    {
247      $orientation = $matches[1];
248      if (in_array($orientation, array(3, 4)))
249      {
250        $rotation = 180;
251      }
252      elseif (in_array($orientation, array(5, 6)))
253      {
254        $rotation = 270;
255      }
256      elseif (in_array($orientation, array(7, 8)))
257      {
258        $rotation = 90;
259      }
260    }
261
262    return $rotation;
263  }
264
265  static function get_rotation_code_from_angle($rotation_angle)
266  {
267    switch($rotation_angle)
268    {
269      case 0:   return 0;
270      case 90:  return 1;
271      case 180: return 2;
272      case 270: return 3;
273    }
274  }
275
276  static function get_rotation_angle_from_code($rotation_code)
277  {
278    switch($rotation_code)
279    {
280      case 0: return 0;
281      case 1: return 90;
282      case 2: return 180;
283      case 3: return 270;
284    }
285  }
286
287  /** Returns a normalized convolution kernel for sharpening*/
288  static function get_sharpen_matrix($amount)
289  {
290                // Amount should be in the range of 28-10
291                $amount = round(abs(-28 + ($amount * 0.18)), 2);
292
293                $matrix = array
294                (
295                        array(-1,   -1,    -1),
296                        array(-1, $amount, -1),
297                        array(-1,   -1,    -1),
298                );
299
300    $norm = array_sum(array_map('array_sum', $matrix));
301
302    for ($i=0; $i<3; $i++)
303    {
304      $line = & $matrix[$i];
305      for ($j=0; $j<3; $j++)
306        $line[$j] /= $norm;
307    }
308
309                return $matrix;
310  }
311
312  private function get_resize_result($destination_filepath, $width, $height, $time=null)
313  {
314    return array(
315      'source'      => $this->source_filepath,
316      'destination' => $destination_filepath,
317      'width'       => $width,
318      'height'      => $height,
319      'size'        => floor(filesize($destination_filepath) / 1024).' KB',
320      'time'        => $time ? number_format((get_moment() - $time) * 1000, 2, '.', ' ').' ms' : null,
321      'library'     => $this->library,
322    );
323  }
324
325  static function is_imagick()
326  {
327    return (extension_loaded('imagick') and class_exists('Imagick'));
328  }
329
330  static function is_ext_imagick()
331  {
332    global $conf;
333
334    if (!function_exists('exec'))
335    {
336      return false;
337    }
338    @exec($conf['ext_imagick_dir'].'convert -version', $returnarray);
339    if (is_array($returnarray) and !empty($returnarray[0]) and preg_match('/ImageMagick/i', $returnarray[0]))
340    {
341      return true;
342    }
343    return false;
344  }
345
346  static function is_gd()
347  {
348    return function_exists('gd_info');
349  }
350
351  static function get_library($library=null, $extension=null)
352  {
353    global $conf;
354
355    if (is_null($library))
356    {
357      $library = $conf['graphics_library'];
358    }
359
360    // Choose image library
361    switch (strtolower($library))
362    {
363      case 'auto':
364      case 'imagick':
365        if ($extension != 'gif' and self::is_imagick())
366        {
367          return 'imagick';
368        }
369      case 'ext_imagick':
370        if ($extension != 'gif' and self::is_ext_imagick())
371        {
372          return 'ext_imagick';
373        }
374      case 'gd':
375        if (self::is_gd())
376        {
377          return 'gd';
378        }
379      default:
380        if ($library != 'auto')
381        {
382          // Requested library not available. Try another library
383          return self::get_library('auto', $extension);
384        }
385    }
386    return false;
387  }
388
389  function destroy()
390  {
391    if (method_exists($this->image, 'destroy'))
392    {
393      return $this->image->destroy();
394    }
395    return true;
396  }
397}
398
399// +-----------------------------------------------------------------------+
400// |                   Class for Imagick extension                         |
401// +-----------------------------------------------------------------------+
402
403class image_imagick implements imageInterface
404{
405  var $image;
406
407  function __construct($source_filepath)
408  {
409    // A bug cause that Imagick class can not be extended
410    $this->image = new Imagick($source_filepath);
411  }
412
413  function get_width()
414  {
415    return $this->image->getImageWidth();
416  }
417
418  function get_height()
419  {
420    return $this->image->getImageHeight();
421  }
422
423  function set_compression_quality($quality)
424  {
425    return $this->image->setImageCompressionQuality($quality);
426  }
427
428  function crop($width, $height, $x, $y)
429  {
430    return $this->image->cropImage($width, $height, $x, $y);
431  }
432
433  function strip()
434  {
435    return $this->image->stripImage();
436  }
437
438  function rotate($rotation)
439  {
440    $this->image->rotateImage(new ImagickPixel(), -$rotation);
441    $this->image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
442    return true;
443  }
444
445  function resize($width, $height)
446  {
447    $this->image->setInterlaceScheme(Imagick::INTERLACE_LINE);
448   
449    // TODO need to explain this condition
450    if ($this->get_width()%2 == 0
451        && $this->get_height()%2 == 0
452        && $this->get_width() > 3*$width)
453    {
454      $this->image->scaleImage($this->get_width()/2, $this->get_height()/2);
455    }
456
457    return $this->image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 0.9);
458  }
459
460  function sharpen($amount)
461  {
462    $m = pwg_image::get_sharpen_matrix($amount);
463                return  $this->image->convolveImage($m);
464  }
465
466  function compose($overlay, $x, $y, $opacity)
467  {
468    $ioverlay = $overlay->image->image;
469    /*if ($ioverlay->getImageAlphaChannel() !== Imagick::ALPHACHANNEL_OPAQUE)
470    {
471      // Force the image to have an alpha channel
472      $ioverlay->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);
473    }*/
474
475    global $dirty_trick_xrepeat;
476    if ( !isset($dirty_trick_xrepeat) && $opacity < 100)
477    {// NOTE: Using setImageOpacity will destroy current alpha channels!
478      $ioverlay->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity / 100, Imagick::CHANNEL_ALPHA);
479      $dirty_trick_xrepeat = true;
480    }
481
482    return $this->image->compositeImage($ioverlay, Imagick::COMPOSITE_DISSOLVE, $x, $y);
483  }
484
485  function write($destination_filepath)
486  {
487    // use 4:2:2 chroma subsampling (reduce file size by 20-30% with "almost" no human perception)
488    $this->image->setSamplingFactors( array(2,1) );
489    return $this->image->writeImage($destination_filepath);
490  }
491}
492
493// +-----------------------------------------------------------------------+
494// |            Class for ImageMagick external installation                |
495// +-----------------------------------------------------------------------+
496
497class image_ext_imagick implements imageInterface
498{
499  var $imagickdir = '';
500  var $source_filepath = '';
501  var $width = '';
502  var $height = '';
503  var $commands = array();
504
505  function __construct($source_filepath)
506  {
507    global $conf;
508    $this->source_filepath = $source_filepath;
509    $this->imagickdir = $conf['ext_imagick_dir'];
510
511    $command = $this->imagickdir.'identify -format "%wx%h" "'.realpath($source_filepath).'"';
512    @exec($command, $returnarray);
513    if(!is_array($returnarray) or empty($returnarray[0]) or !preg_match('/^(\d+)x(\d+)$/', $returnarray[0], $match))
514    {
515      die("[External ImageMagick] Corrupt image\n" . var_export($returnarray, true));
516    }
517
518    $this->width = $match[1];
519    $this->height = $match[2];
520  }
521
522  function add_command($command, $params=null)
523  {
524    $this->commands[$command] = $params;
525  }
526
527  function get_width()
528  {
529    return $this->width;
530  }
531
532  function get_height()
533  {
534    return $this->height;
535  }
536
537  function crop($width, $height, $x, $y)
538  {
539    $this->add_command('crop', $width.'x'.$height.'+'.$x.'+'.$y);
540    return true;
541  }
542
543  function strip()
544  {
545    $this->add_command('strip');
546    return true;
547  }
548
549  function rotate($rotation)
550  {
551    $this->add_command('rotate', -$rotation);
552    $this->add_command('orient', 'top-left');
553    return true;
554  }
555
556  function set_compression_quality($quality)
557  {
558    $this->add_command('quality', $quality);
559    return true;
560  }
561
562  function resize($width, $height)
563  {
564    $this->add_command('interlace', 'line');
565    $this->add_command('filter', 'Lanczos');
566    $this->add_command('resize', $width.'x'.$height.'!');
567    return true;
568  }
569
570  function sharpen($amount)
571  {
572    $m = pwg_image::get_sharpen_matrix($amount);
573
574    $param ='convolve "'.count($m).':';
575    foreach ($m as $line)
576    {
577      $param .= ' ';
578      $param .= implode(',', $line);
579    }
580    $param .= '"';
581    $this->add_command('morphology', $param);
582    return true;
583  }
584
585  function compose($overlay, $x, $y, $opacity)
586  {
587    $param = 'compose dissolve -define compose:args='.$opacity;
588    $param .= ' '.escapeshellarg(realpath($overlay->image->source_filepath));
589    $param .= ' -gravity NorthWest -geometry +'.$x.'+'.$y;
590    $param .= ' -composite';
591    $this->add_command($param);
592    return true;
593  }
594
595  function write($destination_filepath)
596  {
597    $exec = $this->imagickdir.'convert';
598    $exec .= ' "'.realpath($this->source_filepath).'"';
599
600    foreach ($this->commands as $command => $params)
601    {
602      $exec .= ' -'.$command;
603      if (!empty($params))
604      {
605        $exec .= ' '.$params;
606      }
607    }
608
609    $dest = pathinfo($destination_filepath);
610    $exec .= ' "'.realpath($dest['dirname']).'/'.$dest['basename'].'"';
611    @exec($exec, $returnarray);
612
613    //echo($exec);
614    return is_array($returnarray);
615  }
616}
617
618// +-----------------------------------------------------------------------+
619// |                       Class for GD library                            |
620// +-----------------------------------------------------------------------+
621
622class image_gd implements imageInterface
623{
624  var $image;
625  var $quality = 95;
626
627  function __construct($source_filepath)
628  {
629    $gd_info = gd_info();
630    $extension = strtolower(get_extension($source_filepath));
631
632    if (in_array($extension, array('jpg', 'jpeg')))
633    {
634      $this->image = imagecreatefromjpeg($source_filepath);
635    }
636    else if ($extension == 'png')
637    {
638      $this->image = imagecreatefrompng($source_filepath);
639    }
640    elseif ($extension == 'gif' and $gd_info['GIF Read Support'] and $gd_info['GIF Create Support'])
641    {
642      $this->image = imagecreatefromgif($source_filepath);
643    }
644    else
645    {
646      die('[Image GD] unsupported file extension');
647    }
648  }
649
650  function get_width()
651  {
652    return imagesx($this->image);
653  }
654
655  function get_height()
656  {
657    return imagesy($this->image);
658  }
659
660  function crop($width, $height, $x, $y)
661  {
662    $dest = imagecreatetruecolor($width, $height);
663
664    imagealphablending($dest, false);
665    imagesavealpha($dest, true);
666    if (function_exists('imageantialias'))
667    {
668      imageantialias($dest, true);
669    }
670
671    $result = imagecopymerge($dest, $this->image, 0, 0, $x, $y, $width, $height, 100);
672
673    if ($result !== false)
674    {
675      imagedestroy($this->image);
676      $this->image = $dest;
677    }
678    else
679    {
680      imagedestroy($dest);
681    }
682    return $result;
683  }
684
685  function strip()
686  {
687    return true;
688  }
689
690  function rotate($rotation)
691  {
692    $dest = imagerotate($this->image, $rotation, 0);
693    imagedestroy($this->image);
694    $this->image = $dest;
695    return true;
696  }
697
698  function set_compression_quality($quality)
699  {
700    $this->quality = $quality;
701    return true;
702  }
703
704  function resize($width, $height)
705  {
706    $dest = imagecreatetruecolor($width, $height);
707
708    imagealphablending($dest, false);
709    imagesavealpha($dest, true);
710    if (function_exists('imageantialias'))
711    {
712      imageantialias($dest, true);
713    }
714
715    $result = imagecopyresampled($dest, $this->image, 0, 0, 0, 0, $width, $height, $this->get_width(), $this->get_height());
716
717    if ($result !== false)
718    {
719      imagedestroy($this->image);
720      $this->image = $dest;
721    }
722    else
723    {
724      imagedestroy($dest);
725    }
726    return $result;
727  }
728
729  function sharpen($amount)
730  {
731    $m = pwg_image::get_sharpen_matrix($amount);
732                return imageconvolution($this->image, $m, 1, 0);
733  }
734
735  function compose($overlay, $x, $y, $opacity)
736  {
737    $ioverlay = $overlay->image->image;
738    /* A replacement for php's imagecopymerge() function that supports the alpha channel
739    See php bug #23815:  http://bugs.php.net/bug.php?id=23815 */
740
741    $ow = imagesx($ioverlay);
742    $oh = imagesy($ioverlay);
743
744                // Create a new blank image the site of our source image
745                $cut = imagecreatetruecolor($ow, $oh);
746
747                // Copy the blank image into the destination image where the source goes
748                imagecopy($cut, $this->image, 0, 0, $x, $y, $ow, $oh);
749
750                // Place the source image in the destination image
751                imagecopy($cut, $ioverlay, 0, 0, 0, 0, $ow, $oh);
752                imagecopymerge($this->image, $cut, $x, $y, 0, 0, $ow, $oh, $opacity);
753    imagedestroy($cut);
754    return true;
755  }
756
757  function write($destination_filepath)
758  {
759    $extension = strtolower(get_extension($destination_filepath));
760
761    if ($extension == 'png')
762    {
763      imagepng($this->image, $destination_filepath);
764    }
765    elseif ($extension == 'gif')
766    {
767      imagegif($this->image, $destination_filepath);
768    }
769    else
770    {
771      imagejpeg($this->image, $destination_filepath, $this->quality);
772    }
773  }
774
775  function destroy()
776  {
777    imagedestroy($this->image);
778  }
779}
780
781?>
Note: See TracBrowser for help on using the repository browser.