目錄
1、概述
2、安装配置Laravel项目
3、Croppic选项
4、前端
Upload and edit images in Laravel using Croppic jQuery plugin
5、路由
6、后端逻辑
首頁 後端開發 php教程 在 Laravel 5 中使用 jQuery 插件 Croppic + Intervention Image 实现图片上传和裁剪

在 Laravel 5 中使用 jQuery 插件 Croppic + Intervention Image 实现图片上传和裁剪

Jun 23, 2016 pm 01:13 PM

1、概述

我们经常需要为用户头像编写图片上传组件并实现裁剪功能,而每个网站布局都有自己的自定义尺寸,这导致在服务器上裁剪图片可能会造成图片失真,正因如此我更喜欢在客户端编辑图片,而且最近我找到一个jQuery插件可以很轻松地实现这种功能,这个jQuery插件就是 Croppic 。

其工作方式和Twitter、Facebook或LinkedIn的用户头像组件一样,首先用户选择需要操作的图片,然后会提供给用户滑动和缩放选项,当感觉合适了就可以点击裁剪按钮,是不是很简单?

Croppic的工作方式如下:

  • 在浏览器窗口选择图片上传到服务器
  • 服务器返回刚刚上传的图片链接,Croppic通过该链接渲染图片
  • 用户可以滑动、缩放图片,当点击裁剪按钮后图片数据被发送到服务器
  • 服务器接收到图片的原始链接以及裁剪细节:x坐标,y坐标,裁剪宽度,高度,角度
  • 服务器使用裁剪细节数据处理图片后发送成功响应到客户端
  • 如果整个过程中出现错误,会弹出包含错误信息的对话框
  • 裁剪成功后,最终的图片会显示在用户的Croppic盒子里
  • 用户可以点击关闭按钮然后重新操作整个过程

在本教程中我们使用Intervention Image扩展包来进行服务器端的图片处理。

注:本教程的完整代码可以在Github上找到: https://github.com/codingo-me/laravel-croppic

2、安装配置Laravel项目

在继续本教程之前需要先创建一个Laravel项目 croppic (已创建的略过),并且在 .env 中添加如下配置:

URL=http://croppic.dev/UPLOAD_PATH=/var/www/croppic/public/uploads/
登入後複製

注:以上域名和路径需要根据你的具体情况做修改。

如果没有安装 intervention/image ,参考这篇教程: 在 Laravel 5 中集成 Intervention Image 实现对图片的创建、修改和压缩处理

3、Croppic选项

你可以通过JS选项数组来配置几乎所有东西,Croppic可以以内置模态框的形式显示,然后你传递自定义数据到后端,定义缩放/旋转因子,定义图片输出元素,或者自定义上传按钮。

可以通过FileReader API在客户端初始化图片上传,这样你可以跳过上面Croppic工作方式的前两个步骤,但是这种解决方案有一个缺点——某些浏览器不支持FileReader API。

在这个例子中我们定义上传及裁剪URL,然后手动发送裁剪宽度和高度到后端:

var eyeCandy = $('#cropContainerEyecandy');var croppedOptions = {    uploadUrl: 'upload',    cropUrl: 'crop',    cropData:{        'width' : eyeCandy.width(),        'height': eyeCandy.height()    }};var cropperBox = new Croppic('cropContainerEyecandy', croppedOptions);
登入後複製

eyeCandy 变量标记渲染Croppic的DOM元素,在 croppedOptions 配置中我们使用jQuery来获取 eyeCandy 元素的尺寸,这里我们需要计算尺寸,这是由于我们在前端使用了Bootstrap栅格,因此宽度和高度都会随着窗口的变化而变化。

4、前端

如上所述,我们使用了Bootstrap并且从Croppic官网直接下载了自定义样式( home.blade.php ):

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Upload and edit images in Laravel using Croppic jQuery plugin</title>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>    <link rel="stylesheet" href="plugins/croppic/assets/css/main.css"/>    <link rel="stylesheet" href="plugins/croppic/assets/css/croppic.css"/>    <link href='http://fonts.googleapis.com/css?family=Lato:300,400,900' rel='stylesheet' type='text/css'>    <link href='http://fonts.googleapis.com/css?family=Mrs+Sheppards⊂=latin,latin-ext' rel='stylesheet' type='text/css'></head><body><div class="container">    <div class="row margin-bottom-40">        <div class="col-md-12">            <h1 id="Upload-and-edit-images-in-Laravel-using-Croppic-jQuery-plugin">Upload and edit images in Laravel using Croppic jQuery plugin</h1>        </div>    </div>    <div class="row margin-bottom-40">        <div class=" col-md-3">            <div id="cropContainerEyecandy"></div>        </div>    </div>    <div class="row">        <div class="col-md-12">            <p><a href="http://www.croppic.net/" target="_blank">Croppic</a> is ideal for uploading profile photos,        or photos where you require predefined size/ratio.</p>        </div>    </div></div><script src=" https://code.jquery.com/jquery-2.1.3.min.js"></script><script src="plugins/croppic/croppic.min.js"></script><script> var eyeCandy = $('#cropContainerEyecandy'); var croppedOptions = { uploadUrl: 'upload', cropUrl: 'crop', cropData:{ 'width' : eyeCandy.width(), 'height': eyeCandy.height() } }; var cropperBox = new Croppic('cropContainerEyecandy', croppedOptions);</script></body></html>
登入後複製

5、路由

我们需要3个路由,一个用于首页,一个用于上传post请求,还有一个用于裁剪post请求:

<?phpRoute::get('/', 'CropController@getHome');Route::post('upload', 'CropController@postUpload');Route::post('crop', 'CropController@postCrop');
登入後複製

根据以往经验我们知道Laravel会抛出CSRF token错误,因此我们在CSRF中间件中将裁剪和上传操作予以排除:

<?phpnamespace App\Http\Middleware;use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;class VerifyCsrfToken extends BaseVerifier{    /**     * The URIs that should be excluded from CSRF verification.     *     * @var array     */    protected $except = [        'upload',        'crop'    ];}
登入後複製

6、后端逻辑

Image模型和迁移文件

这里我们使用数据库保存图片以便跟踪图片上传,通常在图片和用户之间还会建立关联,从而将用户和图片关联起来。

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class Image extends Model{    protected $table = 'images';    public static $rules = [        'img' => 'required|mimes:png,gif,jpeg,jpg,bmp'    ];    public static $messages = [        'img.mimes' => 'Uploaded file is not in image format',        'img.required' => 'Image is required'    ];}
登入後複製

通常我习惯将模型类放到独立的目录 app/Models 中。

以下是创建 images 表的迁移文件:

<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateImages extends Migration{    /** * Run the migrations. * * @return void */    public function up()    {        Schema::create('images', function (Blueprint $table) {            $table->increments('id');            $table->text('original_name');            $table->text('filename');            $table->timestamps();        });    }    /** * Reverse the migrations. * * @return void */    public function down()    {        Schema::drop('images');    }}
登入後複製

你需要创建新的数据库和数据库用户,然后将配置及凭证信息配置到 .env 中对应选项,完成这些操作之后就可以运行迁移命令: php artisan migrate 。

上传图片逻辑

该方法在用户从浏览器对话框选择图片之后会立即调用:

public function postUpload(){        $form_data = Input::all();        $validator = Validator::make($form_data, Image::$rules, Image::$messages);        if ($validator->fails()) {            return Response::json([                'status' => 'error',                'message' => $validator->messages()->first(),            ], 200);        }        $photo = $form_data['img'];        $original_name = $photo->getClientOriginalName();        $original_name_without_ext = substr($original_name, 0, strlen($original_name) - 4);        $filename = $this->sanitize($original_name_without_ext);        $allowed_filename = $this->createUniqueFilename( $filename );        $filename_ext = $allowed_filename .'.jpg';        $manager = new ImageManager();        $image = $manager->make( $photo )->encode('jpg')->save(env('UPLOAD_PATH') . $filename_ext );        if( !$image) {            return Response::json([                'status' => 'error',                'message' => 'Server error while uploading',            ], 200);        }        $database_image = new Image;        $database_image->filename      = $allowed_filename;        $database_image->original_name = $original_name;        $database_image->save();        return Response::json([            'status'    => 'success',            'url'       => env('URL') . 'uploads/' . $filename_ext,            'width'     => $image->width(),            'height'    => $image->height()        ], 200);}
登入後複製

首先我使用 Image 模型的验证数组验证输入,在那里我指定了图片格式并声明图片是必填项。你也可以添加其它约束,比如图片尺寸等。

如果验证失败,后台会发送错误响应,Croppic也会弹出错误对话框。

注:原生的弹出框看上去真的很丑,所以我总是使用SweetAlert,要使用SweetAlert可以在 croppic.js 文件中搜索alert并将改行替换成: sweetAlert("Oops...", response.message, 'error'); 当然你还要在HTML中引入SweetAlert相关css和js文件。

我们使用 sanitize 和 createUniqueFilename 方法创建服务器端文件名,通常我还会创建 ImageRepository 并将所有所有方法放置到其中,但是这种方式更简单:

private function sanitize($string, $force_lowercase = true, $anal = false){        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",            "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",            "&acirc;€”", "&acirc;€“", ",", "<", ".", ">", "/", "?");        $clean = trim(str_replace($strip, "", strip_tags($string)));        $clean = preg_replace('/\s+/', "-", $clean);        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;        return ($force_lowercase) ?            (function_exists('mb_strtolower')) ?                mb_strtolower($clean, 'UTF-8') :                strtolower($clean) :            $clean;}private function createUniqueFilename( $filename ){        $upload_path = env('UPLOAD_PATH');        $full_image_path = $upload_path . $filename . '.jpg';        if ( File::exists( $full_image_path ) )        {            // Generate token for image            $image_token = substr(sha1(mt_rand()), 0, 5);            return $filename . '-' . $image_token;        }        return $filename;}
登入後複製

创建完独立的文件名后,我们使用Intervention Image提供的 ImageManger 来保存上传的图片。从上传方法返回的响应中Croppic需要如下字段:保存图片的 status 、 url 、 width 和 height 。

裁剪图片逻辑

用户点击裁剪按钮后,Croppic会将用户数据发送到后端路由以便对图片执行裁剪。到这里,你应该看到了,Croppic不做任何实际裁剪工作:-),它只负责发送x/y坐标以及裁剪的宽度和高度数据,具体的裁剪实现逻辑还需要在后台编写。Croppic项目为此提供了一些相关的php脚本,但这里我们仍然选择使用Intervention Image扩展包提供的方法:

public function postCrop(){        $form_data = Input::all();        $image_url = $form_data['imgUrl'];        // resized sizes        $imgW = $form_data['imgW'];        $imgH = $form_data['imgH'];        // offsets        $imgY1 = $form_data['imgY1'];        $imgX1 = $form_data['imgX1'];        // crop box        $cropW = $form_data['width'];        $cropH = $form_data['height'];        // rotation angle        $angle = $form_data['rotation'];        $filename_array = explode('/', $image_url);        $filename = $filename_array[sizeof($filename_array)-1];        $manager = new ImageManager();        $image = $manager->make( $image_url );        $image->resize($imgW, $imgH)            ->rotate(-$angle)            ->crop($cropW, $cropH, $imgX1, $imgY1)            ->save(env('UPLOAD_PATH') . 'cropped-' . $filename);        if( !$image) {            return Response::json([                'status' => 'error',                'message' => 'Server error while uploading',            ], 200);        }        return Response::json([            'status' => 'success',            'url' => env('URL') . 'uploads/cropped-' . $filename        ], 200);}
登入後複製

完整的控制器 CropController 看上去应该是这样的:

<?phpnamespace App\Http\Controllers;use App\Models\Image;use Illuminate\Support\Facades\Validator;use Illuminate\Support\Facades\Input;use Illuminate\Support\Facades\Response;use Intervention\Image\ImageManager;use Illuminate\Support\Facades\File;class CropController extends Controller{    public function getHome()    {        return view('home');    }    public function postUpload()    {        $form_data = Input::all();        $validator = Validator::make($form_data, Image::$rules, Image::$messages);        if ($validator->fails()) {            return Response::json([                'status' => 'error',                'message' => $validator->messages()->first(),            ], 200);        }        $photo = $form_data['img'];        $original_name = $photo->getClientOriginalName();        $original_name_without_ext = substr($original_name, 0, strlen($original_name) - 4);        $filename = $this->sanitize($original_name_without_ext);        $allowed_filename = $this->createUniqueFilename( $filename );        $filename_ext = $allowed_filename .'.jpg';        $manager = new ImageManager();        $image = $manager->make( $photo )->encode('jpg')->save(env('UPLOAD_PATH') . $filename_ext );        if( !$image) {            return Response::json([                'status' => 'error',                'message' => 'Server error while uploading',            ], 200);        }        $database_image = new Image;        $database_image->filename      = $allowed_filename;        $database_image->original_name = $original_name;        $database_image->save();        return Response::json([            'status'    => 'success',            'url'       => env('URL') . 'uploads/' . $filename_ext,            'width'     => $image->width(),            'height'    => $image->height()        ], 200);    }    public function postCrop()    {        $form_data = Input::all();        $image_url = $form_data['imgUrl'];        // resized sizes        $imgW = $form_data['imgW'];        $imgH = $form_data['imgH'];        // offsets        $imgY1 = $form_data['imgY1'];        $imgX1 = $form_data['imgX1'];        // crop box        $cropW = $form_data['width'];        $cropH = $form_data['height'];        // rotation angle        $angle = $form_data['rotation'];        $filename_array = explode('/', $image_url);        $filename = $filename_array[sizeof($filename_array)-1];        $manager = new ImageManager();        $image = $manager->make( $image_url );        $image->resize($imgW, $imgH)            ->rotate(-$angle)            ->crop($cropW, $cropH, $imgX1, $imgY1)            ->save(env('UPLOAD_PATH') . 'cropped-' . $filename);        if( !$image) {            return Response::json([                'status' => 'error',                'message' => 'Server error while uploading',            ], 200);        }        return Response::json([            'status' => 'success',            'url' => env('URL') . 'uploads/cropped-' . $filename        ], 200);    }    private function sanitize($string, $force_lowercase = true, $anal = false)    {        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",            "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",            "&acirc;€”", "&acirc;€“", ",", "<", ".", ">", "/", "?");        $clean = trim(str_replace($strip, "", strip_tags($string)));        $clean = preg_replace('/\s+/', "-", $clean);        $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;        return ($force_lowercase) ?            (function_exists('mb_strtolower')) ?                mb_strtolower($clean, 'UTF-8') :                strtolower($clean) :            $clean;    }    private function createUniqueFilename( $filename )    {        $upload_path = env('UPLOAD_PATH');        $full_image_path = $upload_path . $filename . '.jpg';        if ( File::exists( $full_image_path ) )        {            // Generate token for image            $image_token = substr(sha1(mt_rand()), 0, 5);            return $filename . '-' . $image_token;        }        return $filename;    }}
登入後複製

如果操作成功,后台会返回裁剪后的图片链接,然后Croppic根据此链接显示新的图片。

声明:本文为译文,原文链接: https://tuts.codingo.me/upload-and-edit-image-using-croppic-jquery-plugin

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

描述紮實的原則及其如何應用於PHP的開發。 描述紮實的原則及其如何應用於PHP的開發。 Apr 03, 2025 am 12:04 AM

SOLID原則在PHP開發中的應用包括:1.單一職責原則(SRP):每個類只負責一個功能。 2.開閉原則(OCP):通過擴展而非修改實現變化。 3.里氏替換原則(LSP):子類可替換基類而不影響程序正確性。 4.接口隔離原則(ISP):使用細粒度接口避免依賴不使用的方法。 5.依賴倒置原則(DIP):高低層次模塊都依賴於抽象,通過依賴注入實現。

如何在系統重啟後自動設置unixsocket的權限? 如何在系統重啟後自動設置unixsocket的權限? Mar 31, 2025 pm 11:54 PM

如何在系統重啟後自動設置unixsocket的權限每次系統重啟後,我們都需要執行以下命令來修改unixsocket的權限:sudo...

解釋PHP中晚期靜態結合的概念。 解釋PHP中晚期靜態結合的概念。 Mar 21, 2025 pm 01:33 PM

文章討論了PHP 5.3中介紹的PHP中的晚期靜態結合(LSB),允許靜態方法的運行時間分辨率調用以更靈活的繼承。 LSB的實用應用和潛在的觸摸

如何用PHP的cURL庫發送包含JSON數據的POST請求? 如何用PHP的cURL庫發送包含JSON數據的POST請求? Apr 01, 2025 pm 03:12 PM

使用PHP的cURL庫發送JSON數據在PHP開發中,經常需要與外部API進行交互,其中一種常見的方式是使用cURL庫發送POST�...

框架安全功能:防止漏洞。 框架安全功能:防止漏洞。 Mar 28, 2025 pm 05:11 PM

文章討論了框架中的基本安全功能,以防止漏洞,包括輸入驗證,身份驗證和常規更新。

自定義/擴展框架:如何添加自定義功能。 自定義/擴展框架:如何添加自定義功能。 Mar 28, 2025 pm 05:12 PM

本文討論了將自定義功能添加到框架上,專注於理解體系結構,識別擴展點以及集成和調試的最佳實踐。

See all articles