ImageField.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. *
  41. * @return mixed
  42. */
  43. public function callInterventionMethods($target, $mime)
  44. {
  45. if (! empty($this->interventionCalls)) {
  46. $image = ImageManagerStatic::make($target);
  47. $mime = $mime ?: finfo_file(finfo_open(FILEINFO_MIME_TYPE), $target);
  48. foreach ($this->interventionCalls as $call) {
  49. call_user_func_array(
  50. [$image, $call['method']],
  51. $call['arguments']
  52. )->save($target, null, $mime);
  53. }
  54. }
  55. return $target;
  56. }
  57. /**
  58. * Call intervention methods.
  59. *
  60. * @param string $method
  61. * @param array $arguments
  62. *
  63. * @throws \Exception
  64. *
  65. * @return $this
  66. */
  67. public function __call($method, $arguments)
  68. {
  69. if (static::hasMacro($method)) {
  70. return parent::__call($method, $arguments);
  71. }
  72. if (! class_exists(ImageManagerStatic::class)) {
  73. throw new AdminException('To use image handling and manipulation, please install [intervention/image] first.');
  74. }
  75. $this->interventionCalls[] = [
  76. 'method' => static::$interventionAlias[$method] ?? $method,
  77. 'arguments' => $arguments,
  78. ];
  79. return $this;
  80. }
  81. /**
  82. * @param string|array $name
  83. * @param int $width
  84. * @param int $height
  85. *
  86. * @return $this
  87. */
  88. public function thumbnail($name, int $width = null, int $height = null)
  89. {
  90. if (func_num_args() == 1 && is_array($name)) {
  91. foreach ($name as $key => $size) {
  92. if (count($size) >= 2) {
  93. $this->thumbnails[$key] = $size;
  94. }
  95. }
  96. } elseif (func_num_args() == 3) {
  97. $this->thumbnails[$name] = [$width, $height];
  98. }
  99. return $this;
  100. }
  101. /**
  102. * Destroy original thumbnail files.
  103. *
  104. * @param string|array $file
  105. * @param bool $force
  106. *
  107. * @return void.
  108. */
  109. public function destroyThumbnail($file = null, bool $force = false)
  110. {
  111. if ($this->retainable && ! $force) {
  112. return;
  113. }
  114. $file = $file ?: $this->original;
  115. if (! $file) {
  116. return;
  117. }
  118. if (is_array($file)) {
  119. foreach ($file as $f) {
  120. $this->destroyThumbnail($f);
  121. }
  122. return;
  123. }
  124. foreach ($this->thumbnails as $name => $_) {
  125. // We need to get extension type ( .jpeg , .png ...)
  126. $ext = pathinfo($file, PATHINFO_EXTENSION);
  127. // We remove extension from file name so we can append thumbnail type
  128. $path = Str::replaceLast('.'.$ext, '', $file);
  129. // We merge original name + thumbnail name + extension
  130. $path = $path.'-'.$name.'.'.$ext;
  131. if ($this->getStorage()->exists($path)) {
  132. $this->getStorage()->delete($path);
  133. }
  134. }
  135. }
  136. /**
  137. * Upload file and delete original thumbnail files.
  138. *
  139. * @param UploadedFile $file
  140. *
  141. * @return $this
  142. */
  143. protected function uploadAndDeleteOriginalThumbnail(UploadedFile $file)
  144. {
  145. foreach ($this->thumbnails as $name => $size) {
  146. // We need to get extension type ( .jpeg , .png ...)
  147. $ext = pathinfo($this->name, PATHINFO_EXTENSION);
  148. // We remove extension from file name so we can append thumbnail type
  149. $path = Str::replaceLast('.'.$ext, '', $this->name);
  150. // We merge original name + thumbnail name + extension
  151. $path = $path.'-'.$name.'.'.$ext;
  152. /** @var \Intervention\Image\Image $image */
  153. $image = InterventionImage::make($file);
  154. $action = $size[2] ?? 'resize';
  155. // Resize image with aspect ratio
  156. $image->$action($size[0], $size[1], function (Constraint $constraint) {
  157. $constraint->aspectRatio();
  158. });
  159. if (! is_null($this->storagePermission)) {
  160. $this->getStorage()->put("{$this->getDirectory()}/{$path}", $image->encode(), $this->storagePermission);
  161. } else {
  162. $this->getStorage()->put("{$this->getDirectory()}/{$path}", $image->encode());
  163. }
  164. }
  165. $this->destroyThumbnail();
  166. return $this;
  167. }
  168. }