add LICENSE file
[ouya-imagestore.git] / src / imagestore / Controller / Image.php
1 <?php
2 namespace imagestore;
3
4 class Controller_Image extends Controller_Base
5 {
6     public function handle($uri)
7     {
8         if (!isset($_GET['path'])) {
9             return $this->error('400 Bad request', 'Path missing');
10         }
11
12         $path = $GLOBALS['imagestore']['basedir'] . $_GET['path'];
13         if (!file_exists($path)) {
14             return $this->error('404 Not Found', 'File not found');
15         }
16         
17         if (!isset($_GET['w']) && !isset($_GET['h'])) {
18             header('Content-type: image/jpeg');
19             header('Content-length: ' . filesize($path));
20             return readfile($path);
21         }
22         
23         //resize
24         $img = imagecreatefromjpeg($path);
25         $oldX = $oldY = 0;
26         $oldW = imagesx($img);
27         $oldH = imagesy($img);
28
29         if (isset($_GET['w']) && isset($_GET['h'])) {
30             //max. bounding box respecting aspect ratio
31             $newW = (int) $_GET['w'];
32             $newH = (int) $_GET['h'];
33
34             $rW = $oldW / $newW;
35             $rH = $oldH / $newH;
36             if ($rW > $rH) {
37                 $newOldW = intval($oldW / $rW * $rH);
38                 $oldX = $oldW / 2 - $newOldW / 2;
39                 $oldW = $newOldW;
40             } else {
41                 $newOldH = intval($oldH / $rH * $rW);
42                 $oldY = $oldH / 2 - $newOldH / 2;
43                 $oldH = $newOldH;
44             }
45         } else if (isset($_GET['w'])) {
46             $newW = (int) $_GET['w'];
47             $newH = intval($newW / $oldW * $oldH);
48         } else {
49             $newH = (int) $_GET['h'];
50             $newW = intval($newH / $oldH * $oldW);
51         }
52         
53         $thumb = imagecreatetruecolor($newW, $newH);
54         // Resize
55         imagecopyresampled(
56             $thumb, $img, 0, 0, $oldX, $oldY,
57             $newW, $newH, $oldW, $oldH
58         );
59         imagedestroy($img);
60
61         header('Content-type: image/jpeg');
62         imagejpeg($thumb);
63         imagedestroy($thumb);
64     }
65 }
66 ?>