ImageField.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Exception\AdminException;
  4. use Illuminate\Support\Str;
  5. use Intervention\Image\Constraint;
  6. use Intervention\Image\Facades\Image as InterventionImage;
  7. use Intervention\Image\ImageManagerStatic;
  8. use Symfony\Component\HttpFoundation\File\UploadedFile;
  9. trait ImageField
  10. {
  11. /**
  12. * Intervention calls.
  13. *
  14. * @var array
  15. */
  16. protected $interventionCalls = [];
  17. /**
  18. * Thumbnail settings.
  19. *
  20. * @var array
  21. */
  22. protected $thumbnails = [];
  23. protected static $interventionAlias = [
  24. 'filling' => 'fill',
  25. ];
  26. /**
  27. * Default directory for file to upload.
  28. *
  29. * @return mixed
  30. */
  31. public function defaultDirectory()
  32. {
  33. return config('admin.upload.directory.image');
  34. }
  35. /**
  36. * Execute Intervention calls.
  37. *
  38. * @param string $target
  39. * @param string $mime
  40. * @return mixed
  41. */
  42. public function callInterventionMethods($target, $mime)
  43. {
  44. if (! empty($this->interventionCalls)) {
  45. $image = ImageManagerStatic::make($target);
  46. $mime = $mime ?: finfo_file(finfo_open(FILEINFO_MIME_TYPE), $target);
  47. foreach ($this->interventionCalls as $call) {
  48. call_user_func_array(
  49. [$image, $call['method']],
  50. $call['arguments']
  51. )->save($target, null, $mime);
  52. }
  53. }
  54. return $target;
  55. }
  56. /**
  57. * Call intervention methods.
  58. *
  59. * @param string $method
  60. * @param array $arguments
  61. * @return $this
  62. *
  63. * @throws \Exception
  64. */
  65. public function __call($method, $arguments)
  66. {
  67. if (static::hasMacro($method)) {
  68. return parent::__call($method, $arguments);
  69. }
  70. if (! class_exists(ImageManagerStatic::class)) {
  71. throw new AdminException('To use image handling and manipulation, please install [intervention/image] first.');
  72. }
  73. $this->interventionCalls[] = [
  74. 'method' => static::$interventionAlias[$method] ?? $method,
  75. 'arguments' => $arguments,
  76. ];
  77. return $this;
  78. }
  79. /**
  80. * @param string|array $name
  81. * @param int $width
  82. * @param int $height
  83. * @return $this
  84. */
  85. public function thumbnail($name, int $width = null, int $height = null)
  86. {
  87. if (func_num_args() == 1 && is_array($name)) {
  88. foreach ($name as $key => $size) {
  89. if (count($size) >= 2) {
  90. $this->thumbnails[$key] = $size;
  91. }
  92. }
  93. } elseif (func_num_args() == 3) {
  94. $this->thumbnails[$name] = [$width, $height];
  95. }
  96. return $this;
  97. }
  98. /**
  99. * Destroy original thumbnail files.
  100. *
  101. * @param string|array $file
  102. * @param bool $force
  103. * @return void.
  104. */
  105. public function destroyThumbnail($file = null, bool $force = false)
  106. {
  107. if ($this->retainable && ! $force) {
  108. return;
  109. }
  110. $file = $file ?: $this->original;
  111. if (! $file) {
  112. return;
  113. }
  114. if (is_array($file)) {
  115. foreach ($file as $f) {
  116. $this->destroyThumbnail($f, $force);
  117. }
  118. return;
  119. }
  120. foreach ($this->thumbnails as $name => $_) {
  121. // We need to get extension type ( .jpeg , .png ...)
  122. $ext = pathinfo($file, PATHINFO_EXTENSION);
  123. // We remove extension from file name so we can append thumbnail type
  124. $path = Str::replaceLast('.'.$ext, '', $file);
  125. // We merge original name + thumbnail name + extension
  126. $path = $path.'-'.$name.'.'.$ext;
  127. if ($this->getStorage()->exists($path)) {
  128. $this->getStorage()->delete($path);
  129. }
  130. }
  131. }
  132. /**
  133. * Upload file and delete original thumbnail files.
  134. *
  135. * @param UploadedFile $file
  136. * @return $this
  137. */
  138. protected function uploadAndDeleteOriginalThumbnail(UploadedFile $file)
  139. {
  140. foreach ($this->thumbnails as $name => $size) {
  141. // We need to get extension type ( .jpeg , .png ...)
  142. $ext = pathinfo($this->name, PATHINFO_EXTENSION);
  143. // We remove extension from file name so we can append thumbnail type
  144. $path = Str::replaceLast('.'.$ext, '', $this->name);
  145. // We merge original name + thumbnail name + extension
  146. $path = $path.'-'.$name.'.'.$ext;
  147. /** @var \Intervention\Image\Image $image */
  148. $image = InterventionImage::make($file);
  149. $action = $size[2] ?? 'resize';
  150. // Resize image with aspect ratio
  151. $image->$action($size[0], $size[1], function (Constraint $constraint) {
  152. $constraint->aspectRatio();
  153. });
  154. if (! is_null($this->storagePermission)) {
  155. $this->getStorage()->put("{$this->getDirectory()}/{$path}", $image->encode()->stream(), $this->storagePermission);
  156. } else {
  157. $this->getStorage()->put("{$this->getDirectory()}/{$path}", $image->encode()->stream());
  158. }
  159. }
  160. if (! is_array($this->original)) {
  161. $this->destroyThumbnail();
  162. }
  163. return $this;
  164. }
  165. }