tuvshintugs's avatar

How to resize image before storing to digital ocean in laravel 10?

Hello, Guys How to resize the image before upload to digital ocean in laravel 10?. I tried 2, 3 ways when uploading files. But I failed. Please review below my code

first way. resize images before upload file. i thinking not running stream() and __toString() function. Below the show my log

second way. Uploaded directly without resizing the image. But the picture is uploaded, but it not show image

if ($request->file('categoryimg') && $request->get('categorygroupid')) { $category = WhCategory::where('categorygroupid', $request->get('categorygroupid'))->first(); $cdn_url200 = ''; $cdn_url400 = ''; $cdn_url800 = ''; $imgpath200 = ''; $imgpath400 = ''; $imgpath800 = '';

        $client = new S3Client([
            'version' => 'latest',
            'region' => config('filesystems.disks.do_spaces.region'),
            'endpoint' => config('filesystems.disks.do_spaces.endpoint'),
            'use_path_style_endpoint' => false,
            'credentials' => [
                'key' => config('filesystems.disks.do_spaces.key'),
                'secret' => config('filesystems.disks.do_spaces.secret'),
            ],
            // 'use_path_style_endpoint' => config('filesystems.disks.do_spaces.use_path_style_endpoint'),
        ]);

        $realImg = $request->file('categoryimg');
        $fileHashname = $realImg->hashName();
        \Log::info('hash name ='. $fileHashname);
        $imgname = uniqid().'-'.$request->get('categorygroupid').'.png';

        try {
            // First way
            $imgpath200 = 'mechanic/category/200/'.$imgname;
            $resizeImg200 = Image::make($realImg->getRealPath())->resize(200, 200, function($constraint) {
                $constraint->aspectRatio();
                // $constraint->upsize();
            })->encode('png');
            \Log::info('resize image');
            \Log::info((string)$resizeImg200);
            $result = $client->putObject([
                'Bucket' => config('filesystems.disks.do_spaces.bucket'),
                'Key' => $imgpath200,
                'SourceFile' => $resizeImg200->stream()->__toString(),
                'ACL' => 'public-read',
                // 'ContentLength' => $fileSize,
            ]);
            // Second way
            Storage::disk('do_spaces')->put($imgpath200, $request->file('categoryimg')->getRealPath(), 'public');
        } catch(\Exception $e) {

        }
    }
0 likes
1 reply
martinbean's avatar

@tuvshintugs Upload the image, then dispatch a queue job that resizes it to an appropriate maximum size.

You don’t want to try resizing the image during the upload because if the user uploads a massive image, then you’re probably going to hit a memory limit, if the request doesn’t time out first.

Please or to participate in this conversation.