elas
elas

Reputation: 33

Upload image Intervention Image v3.7

The error Unable to decode input is occurred at the line $image = $manager->read($file);. Here is my code:

Controller

public function upload(Request $request)
    {
        try {
            $filePath = 'banners/';

            if (app()->environment('local')) {
                $filePath = 'local/' . $filePath;
            }

            $file = ImageService::processImage($request->file('file'), $filePath, 1920, 1080);

            return response()->json([
                'message' => 'Banner uploaded successfully',
                'url' => $file
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'message' => 'An error occurred',
                'detail' => $e->getMessage()
            ]);
        }
    }

ImageService

public static function processImage($file, $path, int $width = NULL, int $height = NULL)
    {
        try {
            $filePath = $path . auth()->id() . '_' . Str::random(40) . '_' . time() . '.jpg';
            $manager = new ImageManager(Driver::class);

            // $image = $manager->read('file url') -> this work normally

            // A problem here: Unable to decode input
            $image   = $manager->read($file);

            if ($file->getSize() > self::$maxSize || $width || $height) {
                if ($width && ! $height) {
                    $image->resize(width: $width);
                } elseif (! $width && $height) {
                    $image->resize(height: $height);
                } else {
                    $image->resize($width ?? self::$defaultWidth, $height ?? self::$defaultHeight);
                }
            }
            $encoded = $image->encode(new JpegEncoder(quality: 75));
            Storage::put($filePath, $encoded, 'public');

            return $filePath;
        } catch (Exception $e) {
            dd($e->getMessage());
            Log::info('PROCESS IMAGE ERROR: ' . $e->getMessage());
        }
    }

Someone can explain to me how to upload with Intervention Image (v3.7)

Upvotes: 1

Views: 623

Answers (1)

Azraf C.
Azraf C.

Reputation: 1

Here is how I solve it:

$image = $manager->read(file_get_contents($file));

Here is an example: import:

use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;

in Method:

$today = Carbon::now();
$this->_local_path = '/' . $today->year . '/' . $today->month . '/' . $today->day . '/' ;
$name = time() . rand(1001, 9998) . '.' . $file->getClientOriginalExtension();

$manager = new ImageManager(Driver::class);
$image = $manager->read(file_get_contents($file));
$image->toWebp(85);
$newName = str_replace($file->getClientOriginalExtension(), 'webp', $name);
$imgSavePath = Storage::disk('local')->path($this->_local_path);
$image->save($imgSavePath.$newName);

Upvotes: 0

Related Questions