blob: 364b9fa23562fa0619dafde698ee6f759b12a1cb (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
<?php
namespace app\models;
class Photo extends \lithium\data\Model {
//Tells lithium to store it in mongo as a file (gridFS)
protected $_meta = array('source' => 'fs.files');
public $validates = array();
/**
* Generate a cached version under webroot
* @param string $id The image id as in mongodb
* @param array $options Possible values are
* width
* height
* @return mixed
*/
public static function version($id, $options = array()) {
if (!$id)
return false;
// This is the same as Photo::first($id) when called from inside itself
$self = static::first($id);
return ($self) ? $self->generateVersion($options) : false;
}
/**
* Generate a cached version under webroot
* @param Document $self The document from the db
* @param array $options Possible values are
* @return mixed
*/
public function generateVersion($self, $options = array()) {
// This is quite naive, it would fail at .jpeg for example. Be more elaborate on production code!
$type = substr($self->file->file['filename'], -3);
$path = LITHIUM_APP_PATH . "/webroot/image/{$self->_id}";
$originalPath = $path . "." . $type;
// Always create the original variant if it doesnt exist yet. It is needed for resize
if (!file_exists($originalPath))
file_put_contents($originalPath, $self->file->getBytes());
if (isset($options['width']) && isset($options['height'])) {
$width = (int) $options['width'];
$height = (int) $options['height'];
$path .= "_{$width}x{$height}.{$type}";
// This requires imagemagick and access to system calls.
// It is possible to use gd but it is a much worse alternative so please dont.
$convertCommand = "convert $originalPath -resize {$width}x{$height}\> $path";
shell_exec($convertCommand);
// Return data of the resized version
return file_get_contents($path);
}
// If no width/height were set, just return data of the original
return $self->file->getBytes();
}
}
?>
|