Plugin to render thumbs as squares
[bizou.git] / plugins / _disabled / squares / functions.php
1 <?php
2
3 function getPreview($imgFile, $maxSize = THUMB_SIZE)
4 {
5         # example: data/myalbum/100.mypic.jpg
6         $newImgFile = DATA_DIR."/".dirname($imgFile)."/".$maxSize.".".basename($imgFile);
7
8         # if the preview is a symlink, image is already good sized
9         if (is_link($newImgFile)) return $imgFile;
10
11         if (! is_file($newImgFile))
12         {
13                 # this tels the template to flush output after displaying previews
14                 $GLOBALS["generating"] = true;
15
16                 # reset script time limit to 20s (wont work in safe mode)
17                 set_time_limit(20);
18
19                 $ext = strtolower(substr($imgFile, -4));
20                 if ($ext == ".jpg")
21                         $img = imagecreatefromjpeg($imgFile);
22                 else
23                         $img = imagecreatefrompng($imgFile);
24
25                 $w = imagesx($img);
26                 $h = imagesy($img);
27                 # if the image is already small and squared, make a symlink and return it
28                 if ($w <= $maxSize and $h <= $maxSize and $w == $h) {
29                         imagedestroy($img);
30                         symlink($imgFile, $newImgFile);
31                         return $imgFile;
32                 }
33
34                 # config to allow group writable files
35                 umask(DATA_UMASK);
36                 # create the thumbs directory recursively
37                 if (! is_dir(dirname($newImgFile))) mkdir(dirname($newImgFile), 0777, true);
38
39                 if ($w > $h) {
40                       $srcSize = $h;
41                       $srcY = 0;
42                       $srcX = ($w - $srcSize)/2;
43                 } elseif ($w < $h) {
44                       $srcSize = $w;
45                       $srcX = 0;
46                       $srcY = ($h - $srcSize)/2;
47                 } else {
48                       $srcSize = $w;
49                       $srcX = $srcY = 0;
50                 }
51
52                 $newImg = imagecreatetruecolor(THUMB_SIZE, THUMB_SIZE);
53
54                 imagecopyresampled($newImg, $img, 0, 0, $srcX, $srcY, THUMB_SIZE, THUMB_SIZE, $srcSize, $srcSize);
55
56                 if ($ext == ".jpg")
57                         imagejpeg($newImg, $newImgFile);
58                 else
59                         imagepng($newImg, $newImgFile);
60
61                 imagedestroy($img);
62                 imagedestroy($newImg);
63         }
64
65         return $newImgFile;
66 }
67
68
69 ?>