Image.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. ApplicationSettings::RegisterDefaultSetting("images", "upload_location", "image_uploads");
  3. ApplicationSettings::RegisterDefaultSetting("images", "thumbnail_width", "480");
  4. ApplicationSettings::RegisterDefaultSetting("images", "thumbnail_height", "360");
  5. if (!file_exists(ApplicationSettings::GetSetting("images", "upload_location")))
  6. mkdir(ApplicationSettings::GetSetting("images", "upload_location"));
  7. class Image extends DBObject implements JsonSerializable {
  8. public $Path, $ThumbnailPath;
  9. private $Filename, $TempFile;
  10. public static function IsValidType($ext) {
  11. // use a switch because it's quicker than a loop
  12. switch (strtolower($ext)) {
  13. case "bmp":
  14. case "dib":
  15. case "jpeg":
  16. case "jpg":
  17. case "jpe":
  18. case "jfif":
  19. case "gif":
  20. case "tif":
  21. case "tiff":
  22. case "png":
  23. case "ico":
  24. return true;
  25. default:
  26. return false;
  27. }
  28. }
  29. public function __construct($id=0, $tempFile="") {
  30. if (!is_numeric($id)) {
  31. $this->Filename=$id;
  32. $this->TempFile=$tempFile;
  33. $id=0;
  34. }
  35. parent::__construct("images", "image_id", $id);
  36. if ($this->ImageId)
  37. $this->CalculatePaths();
  38. }
  39. private function CalculatePaths() {
  40. $dir=ApplicationSettings::GetSetting("images", "upload_location");
  41. $info=pathinfo($this->ImageFilename);
  42. $this->Path=$dir.'/'.$this->ImageFilename;
  43. $this->ThumbnailPath=$dir.'/'.$info['filename'].'.thumbnail.'.$info['extension'];
  44. }
  45. private function MakeFileName() {
  46. return $this->ImageId."_".Utils::MakeStringUrlSafe($this->Filename);
  47. }
  48. public function Save() {
  49. $newSave=!$this->ImageId;
  50. parent::Save();
  51. if ($newSave&&$this->ImageId) {
  52. $this->ImageFilename=$this->MakeFileName();
  53. $this->CalculatePaths();
  54. if (!move_uploaded_file($this->TempFile, $this->Path))
  55. throw new Exception("Unable to move uploaded file: ".$this->Path.', '.$this->TempFile);
  56. if (class_exists("Imagick")) {
  57. $thumb=new Imagick($this->Path);
  58. $height=ApplicationSettings::GetSetting("images", "thumbnail_height");
  59. $width=ApplicationSettings::GetSetting("images", "thumbnail_width");
  60. $thumb->scaleImage(0, $height);
  61. $thumb->scaleImage($width, 0);
  62. $thumb->writeImage($this->ThumbnailPath);
  63. $thumb->clear();
  64. $thumb->destroy();
  65. } else
  66. copy($this->Path, $this->ThumbnailPath);
  67. parent::Save();
  68. }
  69. }
  70. public function jsonSerialize() {
  71. $obj=parent::jsonSerialize();
  72. $obj->ThumbnailPath=$this->ThumbnailPath;
  73. $obj->Path=$this->Path;
  74. return $obj;
  75. }
  76. }