source: extensions/square_thumbnails/trunk/functions.inc.php @ 9771

Last change on this file since 9771 was 9771, checked in by patdenice, 13 years ago

Add orientation parameter for ratio

File size: 9.2 KB
Line 
1<?php
2
3if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
4
5// Resize function for thumbnails creation page
6function thumbnail_square_resize($info, $path, $newWidth, $newHeight, $tn_ext)
7{
8  global $conf, $lang, $page;
9
10  if ($info !== false)
11  {
12    //someone hooked us - so we skip
13    return $info;
14  }
15
16  if (!function_exists('gd_info'))
17  {
18    return;
19  }
20
21  $filename = basename($path);
22  $dirname = dirname($path);
23 
24  // extension of the picture filename
25  $extension = get_extension($filename);
26
27  if (in_array($extension, array('jpg', 'JPG', 'jpeg', 'JPEG')))
28  {
29    $srcImage = @imagecreatefromjpeg($path);
30  }
31  else if ($extension == 'png' or $extension == 'PNG')
32  {
33    $srcImage = @imagecreatefrompng($path);
34  }
35  else
36  {
37    unset($extension);
38  }
39
40  if ( isset( $srcImage ) )
41  {
42    // width/height
43    $srcWidth    = imagesx( $srcImage ); 
44    $srcHeight   = imagesy( $srcImage ); 
45
46    $coord = process_ratio($srcWidth, $srcHeight);
47
48    $ratioWidth  = $srcWidth/$newWidth;
49    $ratioHeight = $srcHeight/$newHeight;
50
51    // maximal size exceeded ?
52    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
53    {
54      if ( $ratioWidth < $ratioHeight)
55      { 
56        $destWidth = $srcWidth/$ratioHeight;
57        $destHeight = $newHeight; 
58      }
59      else
60      { 
61        $destWidth = $newWidth; 
62        $destHeight = $srcHeight/$ratioWidth;
63      }
64    }
65    else
66    {
67      $destWidth = $srcWidth;
68      $destHeight = $srcHeight;
69    }
70
71    // according to the GD version installed on the server
72    if ( $_POST['gd'] == 2 )
73    {
74      // GD 2.0 or more recent -> good results (but slower)
75      $destImage = imagecreatetruecolor( $destWidth, $destHeight); 
76      imagecopyresampled( $destImage, $srcImage, 0, 0, $coord['x'], $coord['y'],
77                          $destWidth,$destHeight,$srcWidth,$srcHeight );
78    }
79    else
80    {
81      // GD prior to version  2 -> pretty bad results :-/ (but fast)
82      $destImage = imagecreate( $destWidth, $destHeight);
83      imagecopyresized( $destImage, $srcImage, 0, 0, $coord['x'], $coord['y'],
84                        $destWidth,$destHeight,$srcWidth,$srcHeight );
85    }
86
87    if (($tndir = mkget_thumbnail_dir($dirname, $page['errors'])) == false)
88    {
89      return false;
90    }
91
92    $dest_file = $tndir.'/'.$conf['prefix_thumbnail'];
93    $dest_file.= get_filename_wo_extension($filename);
94    $dest_file.= '.'.$tn_ext;
95   
96    // creation and backup of final picture
97    if (!is_writable($tndir))
98    {
99      array_push($page['errors'], '['.$tndir.'] : '.l10n('no write access'));
100      return false;
101    }
102    imagejpeg($destImage, $dest_file, $conf['tn_compression_level']);
103    // freeing memory ressources
104    imagedestroy( $srcImage );
105    imagedestroy( $destImage );
106   
107    list($tn_width, $tn_height) = getimagesize($dest_file);
108    $tn_size = floor(filesize($dest_file) / 1024).' KB';
109   
110    $info = array( 'path'      => $path,
111                   'tn_file'   => $dest_file,
112                   'tn_width'  => $tn_width,
113                   'tn_height' => $tn_height,
114                   'tn_size'   => $tn_size );
115    return $info;
116  }
117  // error
118  else
119  {
120    echo l10n('Picture unreachable or no support')." ";
121    if ( isset( $extenstion ) )
122    {
123      echo l10n('for the file format').' '.$extension;
124    }
125    else
126    {
127      echo l10n('for this file format');
128    }
129    exit();
130  }
131}
132
133
134// Resize function for Upload Form
135function upload_square_resize($result, $source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata=false)
136{
137  if ($result !== false)
138  {
139    //someone hooked us - so we skip
140    return $result;
141  }
142
143  if (is_imagick())
144  {
145    return upload_square_resize_im($source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata);
146  }
147  else
148  {
149    return upload_square_resize_gd($source_filepath, $destination_filepath, $max_width, $max_height, $quality);
150  }
151}
152
153function upload_square_resize_gd($source_filepath, $destination_filepath, $max_width, $max_height, $quality)
154{
155  if (!function_exists('gd_info'))
156  {
157    return false;
158  }
159
160  // extension of the picture filename
161  $extension = strtolower(get_extension($source_filepath));
162
163  $source_image = null;
164  if (in_array($extension, array('jpg', 'jpeg')))
165  {
166    $source_image = @imagecreatefromjpeg($source_filepath);
167  }
168  else if ($extension == 'png')
169  {
170    $source_image = @imagecreatefrompng($source_filepath);
171  }
172  else
173  {
174    die('unsupported file extension');
175  }
176
177  $rotation = null;
178  if (function_exists('imagerotate'))
179  {
180    $rotation = get_rotation_angle($source_filepath);
181  }
182 
183  // width/height
184  $source_width  = imagesx($source_image); 
185  $source_height = imagesy($source_image);
186 
187  $coord = process_ratio($source_width, $source_height);
188
189  $resize_dimensions = get_resize_dimensions($source_width, $source_height, $max_width, $max_height, $rotation);
190
191  // testing on height is useless in theory: if width is unchanged, there
192  // should be no resize, because width/height ratio is not modified.
193  if ($resize_dimensions['width'] == $source_width and $resize_dimensions['height'] == $source_height)
194  {
195    // the image doesn't need any resize! We just copy it to the destination
196    copy($source_filepath, $destination_filepath);
197    return true;
198  }
199 
200  $destination_image = imagecreatetruecolor($resize_dimensions['width'], $resize_dimensions['height']);
201 
202  imagecopyresampled(
203    $destination_image,
204    $source_image,
205    0,
206    0,
207    $coord['x'],
208    $coord['y'],
209    $resize_dimensions['width'],
210    $resize_dimensions['height'],
211    $source_width,
212    $source_height
213    );
214
215  // rotation occurs only on resized photo to avoid useless memory use
216  if (isset($rotation))
217  {
218    $destination_image = imagerotate($destination_image, $rotation, 0);
219  }
220 
221  $extension = strtolower(get_extension($destination_filepath));
222  if ($extension == 'png')
223  {
224    imagepng($destination_image, $destination_filepath);
225  }
226  else
227  {
228    imagejpeg($destination_image, $destination_filepath, $quality);
229  }
230  // freeing memory ressources
231  imagedestroy($source_image);
232  imagedestroy($destination_image);
233
234  // everything should be OK if we are here!
235  return true;
236}
237
238function upload_square_resize_im($source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata=false)
239{
240  // extension of the picture filename
241  $extension = strtolower(get_extension($source_filepath));
242  if (!in_array($extension, array('jpg', 'jpeg', 'png')))
243  {
244    die('[Imagick] unsupported file extension');
245  }
246
247  $image = new Imagick($source_filepath);
248
249  $rotation = get_rotation_angle($source_filepath);
250 
251  // width/height
252  $source_width  = $image->getImageWidth();
253  $source_height = $image->getImageHeight();
254
255  $coord = process_ratio($source_width, $source_height);
256
257  $image->cropImage($source_width, $source_height, $coord['x'], $coord['y']);
258 
259  $resize_dimensions = get_resize_dimensions($source_width, $source_height, $max_width, $max_height, $rotation);
260
261  // testing on height is useless in theory: if width is unchanged, there
262  // should be no resize, because width/height ratio is not modified.
263  if ($resize_dimensions['width'] == $source_width and $resize_dimensions['height'] == $source_height)
264  {
265    // the image doesn't need any resize! We just copy it to the destination
266    copy($source_filepath, $destination_filepath);
267    return true;
268  }
269
270  $image->setImageCompressionQuality($quality);
271  $image->setInterlaceScheme(Imagick::INTERLACE_LINE);
272 
273  if ($strip_metadata)
274  {
275    // we save a few kilobytes. For example a thumbnail with metadata
276    // weights 25KB, without metadata 7KB.
277    $image->stripImage();
278  }
279 
280  $image->resizeImage($resize_dimensions['width'], $resize_dimensions['height'], Imagick::FILTER_LANCZOS, 0.9);
281
282  if (isset($rotation))
283  {
284    $image->rotateImage(new ImagickPixel(), -$rotation);
285    $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
286  }
287
288  $image->writeImage($destination_filepath);
289  $image->destroy();
290
291  // everything should be OK if we are here!
292  return true;
293}
294
295function process_ratio(&$source_width, &$source_height)
296{
297  global $conf;
298
299  if (!isset($conf['thumbnails_ratio']) or !preg_match('/^\d+:\d+$/', $conf['thumbnails_ratio']))
300    $conf['thumbnails_ratio'] = '1:1';
301
302  if (!isset($conf['thumbnails_ratio_orientation']))
303    $conf['thumbnails_ratio_orientation'] = true;
304
305  $x = 0;
306  $y = 0;
307
308  if ($source_width >= $source_height or !$conf['thumbnails_ratio_orientation'])
309    list($widthRatio, $heightRatio) = explode(':', $conf['thumbnails_ratio']);
310  else
311    list($heightRatio, $widthRatio) = explode(':', $conf['thumbnails_ratio']);
312
313  $img_ratio = $source_width / $source_height;
314  $dest_ratio = $widthRatio / $heightRatio;
315
316  if($dest_ratio > $img_ratio)
317  {
318    $destHeight = ceil(($source_width * $heightRatio) / $widthRatio);
319    $y = ceil(($source_height - $destHeight) / 2 );
320    $source_height = $destHeight ;
321  }
322  elseif ($dest_ratio < $img_ratio)
323  {
324    $destWidth = ceil(($source_height * $widthRatio) / $heightRatio);
325    $x = ceil(($source_width - $destWidth) / 2 );
326    $source_width = $destWidth ;
327  }
328
329  return array('x' => $x, 'y' => $y);
330}
331
332add_event_handler('thumbnail_resize', 'thumbnail_square_resize', 40, 5);
333add_event_handler('upload_thumbnail_resize', 'upload_square_resize', 40, 7);
334
335?>
Note: See TracBrowser for help on using the repository browser.