Table des matières
1、概述
2、安装配置Laravel项目
3、Croppic选项
4、前端
Upload and edit images in Laravel using Croppic jQuery plugin
5、路由
6、后端逻辑
Maison développement back-end tutoriel 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/
Copier après la connexion

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

如果没有安装 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);
Copier après la connexion

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>
Copier après la connexion

5、路由

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

<?phpRoute::get('/', 'CropController@getHome');Route::post('upload', 'CropController@postUpload');Route::post('crop', 'CropController@postCrop');
Copier après la connexion

根据以往经验我们知道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'    ];}
Copier après la connexion

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'    ];}
Copier après la connexion

通常我习惯将模型类放到独立的目录 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');    }}
Copier après la connexion

你需要创建新的数据库和数据库用户,然后将配置及凭证信息配置到 .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);}
Copier après la connexion

首先我使用 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;}
Copier après la connexion

创建完独立的文件名后,我们使用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);}
Copier après la connexion

完整的控制器 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;    }}
Copier après la connexion

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

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

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

11 meilleurs scripts de raccourcissement d'URL PHP (gratuit et premium) 11 meilleurs scripts de raccourcissement d'URL PHP (gratuit et premium) Mar 03, 2025 am 10:49 AM

Les longues URL, souvent encombrées de mots clés et de paramètres de suivi, peuvent dissuader les visiteurs. Un script de raccourcissement d'URL offre une solution, créant des liens concis idéaux pour les médias sociaux et d'autres plateformes. Ces scripts sont utiles pour les sites Web individuels

Introduction à l'API Instagram Introduction à l'API Instagram Mar 02, 2025 am 09:32 AM

À la suite de son acquisition de haut niveau par Facebook en 2012, Instagram a adopté deux ensembles d'API pour une utilisation tierce. Ce sont l'API graphique Instagram et l'API d'affichage de base Instagram. En tant que développeur créant une application qui nécessite des informations à partir d'un

Travailler avec les données de session Flash dans Laravel Travailler avec les données de session Flash dans Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifie la gestion des données de session temporaires à l'aide de ses méthodes de flash intuitives. Ceci est parfait pour afficher de brefs messages, alertes ou notifications dans votre application. Les données ne persistent que pour la demande ultérieure par défaut: $ demande-

Construisez une application React avec un Laravel Back End: Partie 2, React Construisez une application React avec un Laravel Back End: Partie 2, React Mar 04, 2025 am 09:33 AM

Il s'agit de la deuxième et dernière partie de la série sur la construction d'une application React avec un back-end Laravel. Dans la première partie de la série, nous avons créé une API RESTful utilisant Laravel pour une application de liste de base sur le produit. Dans ce tutoriel, nous serons Dev

Misque de réponse HTTP simplifié dans les tests Laravel Misque de réponse HTTP simplifié dans les tests Laravel Mar 12, 2025 pm 05:09 PM

Laravel fournit une syntaxe de simulation de réponse HTTP concise, simplifiant les tests d'interaction HTTP. Cette approche réduit considérablement la redondance du code tout en rendant votre simulation de test plus intuitive. L'implémentation de base fournit une variété de raccourcis de type de réponse: Utiliser illuminate \ support \ faades \ http; Http :: faux ([[ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Mar 14, 2025 am 11:42 AM

L'extension PHP Client URL (CURL) est un outil puissant pour les développeurs, permettant une interaction transparente avec des serveurs distants et des API REST. En tirant parti de Libcurl, une bibliothèque de transfert de fichiers multi-protocol très respectée, PHP Curl facilite Efficient Execu

12 meilleurs scripts de chat PHP sur Codecanyon 12 meilleurs scripts de chat PHP sur Codecanyon Mar 13, 2025 pm 12:08 PM

Voulez-vous fournir des solutions instantanées en temps réel aux problèmes les plus pressants de vos clients? Le chat en direct vous permet d'avoir des conversations en temps réel avec les clients et de résoudre leurs problèmes instantanément. Il vous permet de fournir un service plus rapide à votre personnalité

Annonce de l'enquête sur la situation en 2025 PHP Annonce de l'enquête sur la situation en 2025 PHP Mar 03, 2025 pm 04:20 PM

L'enquête sur le paysage PHP 2025 étudie les tendances actuelles de développement du PHP. Il explore l'utilisation du cadre, les méthodes de déploiement et les défis, visant à fournir des informations aux développeurs et aux entreprises. L'enquête prévoit la croissance de la PHP moderne versio

See all articles