使用laravel将裁剪后的图像保存在public / uploads文件夹中

时间:2019-03-14 15:11:45

标签: php laravel

我正在尝试将裁剪的图像上传到laravel中的public / uploads文件夹。 我能够将图像路径保存到数据库,但是无法将裁剪的图像保存到public / uploads文件夹。

这是我的代码的样子:

 $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');
            }

在裁剪功能之后,我试图将裁剪后的图像放入变量中,然后将图像放入public / uploads文件夹中。

1 个答案:

答案 0 :(得分:0)

我真的建议您使用图像干预程序包,该程序包在此类实现中非常方便且干净。

有关安装,请参见here

然后进行裁剪,您可以轻松使用软件包的crop功能:

<?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');