ImageField.php 5.1 KB

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