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

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment