M.Bozuwa
M.Bozuwa

Reputation: 25

Save cropped image in the public/uploads folder with laravel

I am trying to upload the image I cropped to the public/uploads folder in laravel. I am able to save the image path to the database, but I am not able to save the cropped image to the public/uploads folder.

This is how my code looks like:

 $slideshow = \App\Slideshow::find($id);
        //This is the path to the image that's in the database.
        $pieces = explode("/", $slideshow->image);
        $image = $pieces[0]. "/public/". $pieces[1]. "/". $pieces[2];
        $new_image = $pieces[0]. "/public/". $pieces[1]. "/". $pieces[2];
        $image_quality = '95';
        list( $current_width, $current_height ) = getimagesize($new_image);


        //This is the data that gets send from the blade form
        $x1 = $request->input('x1');
        $y1 = $request->input('y1');
        $x2 = $request->input('x2');
        $y2 = $request->input('y2');
        $width = $request->input('width');
        $height = $request->input('height');

        //This function is cropping the image
        $crop_width = 50; 
        $crop_height = 50;
        $new = imagecreatetruecolor( $crop_width, $crop_height );
        $current_image = imagecreatefromjpeg( $new_image );
        imagecopyresampled( $new, $current_image, 0, 0, $x1, $y1, $crop_width, $crop_height, $width, $height );
        imagejpeg( $new, $new_image, $image_quality );
        $final_image = imagejpeg( $new, $new_image, $image_quality );

            if($final_image == true) {
                $image = 'uploads/' . $image['image'];
                $final_image = 'uploads/crop_'. $pieces[2];
                $destination = '../uploads/';
                $complete = $destination.$final_image;

                $slideshow->cropped_image = $complete;
                $slideshow->save();

                Storage::copy($image, $final_image);
                dd(Storage::copy($image, $final_image));

                return redirect()->back();
            } else {
                dd('Doesn't work');
            }

After the crop function I am trying to put the cropped image into a variable and then putting the image in the public/uploads folder.

Upvotes: 1

Views: 939

Answers (1)

Mihir Bhende
Mihir Bhende

Reputation: 9045

I would really recommend using image intervention package which is extremely handy and clean in such implementations.

See here for installation, its pretty straightforward.

And then to crop you can easily use crop functions of the package :

<?php 

    $originalImagePath = '//your_image_path'
    $x = $request->input('x');
    $y = $request->input('y');
    $width = $request->input('width');
    $height = $request->input('height');

    $croppedImage = Image::make($originalImagePath);              
    $croppedImage->crop($width, $height, $x, $y);
    $croppedImage->save('//new_path_here');

Upvotes: 1

Related Questions