monstajamss's avatar

how to Resize image during upload

I am trying to resize image before i upload it i want the width: 736px and height:530px i have this in my controller

public function store(PostRequest $request)
    {  
        if($request->featured_image)
        {
            $exploded = explode(',', $request->featured_image);
            $decoded = base64_decode($exploded[1]);
            $fileName = Str::slug("{$request->title}.jpg");
            $request->merge(['featured_image' => $fileName]);
            Storage::disk('public')->put($fileName, $decoded);
        }

        $post = Post::create([
            'title' => $request->title,
            'body' => $request->body,
            'excerpt' => $request->excerpt,
            'user_id' => auth()->id(),
            'featured_image' => $request->featured_image,
        ]);

        $post->categories()->attach($request->catSelected);
        
        return response()->json([
            'post' => $post,
            'message' => 'Post created successfully.'
        ], 200);
    }

Not sure how to handle the resizing

Any help would be appreciated.

0 likes
6 replies
monstajamss's avatar

@Sergiu17 after installing i did this

if($request->featured_image)
        {
            $exploded = explode(',', $request->featured_image);
            $decoded = base64_decode($exploded[1]);
            $fileName = Str::slug("{$request->title}.jpg");
            $img = Image::make($decoded)->resize(265, 200);
            $request->merge(['featured_image' => $fileName]);
            Storage::disk('public')->put($fileName, $img);
        }

but the file created is not an image so the image is broken... What am i doing wrong?

monstajamss's avatar

@MichalOravec That works but i will like to save the image name as sample-image-post.jpg currently it saves as sample-image-postjpg it saves as jpg instead of .jpg

code here

if($request->featured_image)
        {
            $exploded = explode(',', $request->featured_image);
            $decoded = base64_decode($exploded[1]);
            $fileName = Str::slug("{$request->title}".'.'.'jpg');
            $img = Image::make($decoded)->resize(265, 200)->encode('jpg');
            $request->merge(['featured_image' => $fileName]);
            Storage::disk('public')->put($fileName,(string) $img);
        }
yogesh gohil's avatar

Using this plugin it's very simple to modify any image "image.intervention.io/v2"

Please or to participate in this conversation.