UploadsBase64Image.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Traits;
  3. use Exception;
  4. use Illuminate\Support\Facades\Storage;
  5. use Illuminate\Support\Str;
  6. trait UploadsBase64Image
  7. {
  8. /**
  9. * Upload a base64 encoded image and return the URL.
  10. *
  11. * @throws \Exception
  12. */
  13. public function uploadBase64Image(string $base64Image, string $folder): string
  14. {
  15. // Extract the file extension and base64 data
  16. if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
  17. $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
  18. $type = strtolower($type[1]); // jpg, png, gif
  19. if (! in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
  20. throw new Exception(__('validation.extensions', ['attribute' => __('general.image'), 'values' => 'jpg, jpeg, png, gif']));
  21. }
  22. $image = base64_decode($base64Image);
  23. if ($image === false) {
  24. throw new Exception('Base64 decode failed');
  25. }
  26. } else {
  27. throw new Exception('Invalid base64 image format');
  28. }
  29. // Generate a unique filename
  30. $filename = Str::random(20).'.'.$type;
  31. // Define the full path where the file will be stored
  32. $filePath = $folder.'/'.$filename;
  33. Storage::put($filePath, $image);
  34. return $filePath;
  35. }
  36. }