UploadsBase64Image.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. * @param string $base64Image
  12. * @param string $folder
  13. * @return string
  14. * @throws \Exception
  15. */
  16. public function uploadBase64Image(string $base64Image, string $folder): string
  17. {
  18. // Extract the file extension and base64 data
  19. if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
  20. $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
  21. $type = strtolower($type[1]); // jpg, png, gif
  22. if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
  23. throw new Exception(__('validation.extensions', ['attribute' => __('general.image'), 'values' => 'jpg, jpeg, png, gif']));
  24. }
  25. $image = base64_decode($base64Image);
  26. if ($image === false) {
  27. throw new Exception('Base64 decode failed');
  28. }
  29. } else {
  30. throw new Exception('Invalid base64 image format');
  31. }
  32. // Generate a unique filename
  33. $filename = Str::random(20) . '.' . $type;
  34. // Define the full path where the file will be stored
  35. $filePath = $folder . '/' . $filename;
  36. // Save the file
  37. Storage::put($filePath, $image);
  38. // Return the URL of the uploaded image
  39. return Storage::url($filePath);
  40. }
  41. }