Photo.php 2.2 KB

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