Image Upload and Crop in Modal with Codeigniter, MySql and jQuery
Image uploading and cropping is the most important functionality of any web project.In this article, I have also shared the Live Demo and Source Code to upload and crop images in a boot model using Codeigniter, MySql, and jQuery.This is a simple jQuery image cropping plugin cropper.js.
Step 1: Include JS and CSS file
Open “application/views/crop/index.php” file and add code like as bellow:
1 2 3 4 5 |
<?php <script src="/path/to/jquery.js"></script> <link href="/path/to/cropper.css" rel="stylesheet"> <script src="/path/to/cropper.js"></script> ?> |
Step 2: Create a Model file Cropper
Create a model file named “Cropper.php and Site.php” inside “application/modes” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @package Cropper : CodeIgniter Crop * @author TechArise Team * * @email info@techarise.com * * Description of Cropper Model */ class Cropper extends CI_Model { private $src; private $data; private $dst; private $type; private $extension; private $msg; private $dstThumb; //set Src public function setSrc($src) { if (!empty($src)) { $type = exif_imagetype($src); if($type) { $this ->src = $src; $this ->type = $type; $this ->extension = image_type_to_extension($type); $this ->setDst(); } } } // set Data public function setData($data) { if (!empty($data)) { return $this ->data = json_decode(stripslashes($data)); } } // set File public function setFile($file, $originalPath) { $errorCode = $file['error']; if ($errorCode === UPLOAD_ERR_OK) { if ( function_exists( 'exif_imagetype' ) ) { $type = exif_imagetype($file['tmp_name']); } else { $r = getimagesize( $file['tmp_name'] ); $type = $r[2]; } if ($type) { $extension = image_type_to_extension($type); $src = $originalPath . date('YmdHis').'-original' . $extension; if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) { if (file_exists($src)) { unlink($src); } $result = move_uploaded_file($file['tmp_name'], $src); if ($result) { $this ->src = $src; $this ->type = $type; $this ->extension = $extension; $this ->setDst(true); } else { $this -> msg = 'Failed to save file'; } } else { $this -> msg = 'Please upload image with the following types: JPG, PNG, GIF'; } } else { $this -> msg = 'Please upload image file'; } } else { $this -> msg = $this -> codeToMessage($errorCode); } return $src; } // set Dst public function setDst($thumbPath) { $imageCropName = date('YmdHis') . '.png'; $this ->dstThumb = $imageCropName; return $this ->dst = $thumbPath . $imageCropName; } // crop image public function crop($src, $dst, $data) { if (!empty($src) && !empty($dst) && !empty($data)) { switch ($this ->type) { case IMAGETYPE_GIF: $src_img = imagecreatefromgif($src); break; case IMAGETYPE_JPEG: $src_img = imagecreatefromjpeg($src); break; case IMAGETYPE_PNG: $src_img = imagecreatefrompng($src); break; } if (!$src_img) { $this -> msg = "Failed to read the image file"; return; } $size = getimagesize($src); $size_w = $size[0]; // natural width $size_h = $size[1]; // natural height $src_img_w = $size_w; $src_img_h = $size_h; $degrees = $data ->rotate; // Rotate the source image if (is_numeric($degrees) && $degrees != 0) { // PHP's degrees is opposite to CSS's degrees $new_img = imagerotate( $src_img, -$degrees, imagecolorallocatealpha($src_img, 0, 0, 0, 127) ); imagedestroy($src_img); $src_img = $new_img; $deg = abs($degrees) % 180; $arc = ($deg > 90 ? (180 - $deg) : $deg) * M_PI / 180; $src_img_w = $size_w * cos($arc) + $size_h * sin($arc); $src_img_h = $size_w * sin($arc) + $size_h * cos($arc); // Fix rotated image miss 1px issue when degrees < 0 $src_img_w -= 1; $src_img_h -= 1; } $tmp_img_w = $data -> width; $tmp_img_h = $data -> height; $dst_img_w = 220; $dst_img_h = 220; $src_x = $data -> x; $src_y = $data -> y; if ($src_x <= -$tmp_img_w || $src_x > $src_img_w) { $src_x = $src_w = $dst_x = $dst_w = 0; } else if ($src_x <= 0) { $dst_x = -$src_x; $src_x = 0; $src_w = $dst_w = min($src_img_w, $tmp_img_w + $src_x); } else if ($src_x <= $src_img_w) { $dst_x = 0; $src_w = $dst_w = min($tmp_img_w, $src_img_w - $src_x); } if ($src_w <= 0 || $src_y <= -$tmp_img_h || $src_y > $src_img_h) { $src_y = $src_h = $dst_y = $dst_h = 0; } else if ($src_y <= 0) { $dst_y = -$src_y; $src_y = 0; $src_h = $dst_h = min($src_img_h, $tmp_img_h + $src_y); } else if ($src_y <= $src_img_h) { $dst_y = 0; $src_h = $dst_h = min($tmp_img_h, $src_img_h - $src_y); } // Scale to destination position and size $ratio = $tmp_img_w / $dst_img_w; $dst_x /= $ratio; $dst_y /= $ratio; $dst_w /= $ratio; $dst_h /= $ratio; $dst_img = imagecreatetruecolor($dst_img_w, $dst_img_h); // Add transparent background to destination image imagefill($dst_img, 0, 0, imagecolorallocatealpha($dst_img, 0, 0, 0, 127)); imagesavealpha($dst_img, true); $result = imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); if ($result) { if (!imagepng($dst_img, $dst)) { $this -> msg = "Failed to save the cropped image file"; } } else { $this -> msg = "Failed to crop the image file"; } imagedestroy($src_img); imagedestroy($dst_img); } } // codeToMessage public function codeToMessage($code) { $errors = array( UPLOAD_ERR_INI_SIZE =>'The uploaded file exceeds the upload_max_filesize directive in php.ini', UPLOAD_ERR_FORM_SIZE =>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', UPLOAD_ERR_PARTIAL =>'The uploaded file was only partially uploaded', UPLOAD_ERR_NO_FILE =>'No file was uploaded', UPLOAD_ERR_NO_TMP_DIR =>'Missing a temporary folder', UPLOAD_ERR_CANT_WRITE =>'Failed to write file to disk', UPLOAD_ERR_EXTENSION =>'File upload stopped by extension', ); if (array_key_exists($code, $errors)) { return $errors[$code]; } return 'Unknown upload error'; } public function getResult() { return !empty($this ->data) ? $this ->dst : $this ->src; } public function getThumbResult() { return !empty($this ->data) ? $this ->dstThumb : $this ->src; } public function getMsg() { return $this -> msg; } } ?> |
Step 3: Create a Controller file Crop Express
Create a Controller file named “Crop.php” inside “application/controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * @package Crop : CodeIgniter Crop * * @author TechArise Team * * @email info@techarise.com * * Description of Crop Controller */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Crop extends CI_Controller { public function __construct() { parent::__construct(); //$this->load->library('upload'); $this->load->helper(array('form', 'url')); $this->load->model('Site', 'site'); $this->load->model('Cropper', 'cropper'); } // index page public function index() { $data['title'] = 'Image Crop | TechArise'; $this->site->setUserID(1); $data['userInfo'] = $this->site->getUserDetails(); $this->load->view('crop/index', $data); } // crop avtar public function upload() { $json = array(); $avatar_src = $this->input->post('avatar_src'); $avatar_data = $this->input->post('avatar_data'); $avatar_file = $_FILES['avatar_file']; $ussid = $this->input->post('ussid'); $upltype = $this->input->post('upltype'); $originalPath = ROOT_UPLOAD_PATH; $thumbPath = ROOT_UPLOAD_PATH.'_thumb/'; $urlPath = HTTP_USER_PROFILE_THUMB_PATH; $thumb = $this->cropper->setDst($thumbPath); $this->cropper->setSrc($avatar_src); $data = $this->cropper->setData($avatar_data); // set file $avatar_path = $this->cropper->setFile($avatar_file, $originalPath); // crop $this->cropper->crop($avatar_path, $thumb, $data); // response $json = array( 'state' => 200, 'message' => $this->cropper->getMsg(), 'result' => $this->cropper->getResult(), 'thumb' => $this->cropper->getThumbResult(), 'ussid' => $ussid, 'upltype' => $upltype, 'urlPath' => $urlPath, ); echo json_encode($json); } // upload prifile avatar Crop Image public function uploadCropImg() { $json = array(); $image_url = $this->input->post('image_url'); $user_id = base64_decode($this->input->post('member_id')); $upltype = $this->input->post('upltype'); if (!empty($user_id) && !empty($upltype) && $upltype=='avatar') { $this->site->seturl($image_url); $this->site->setUserID($user_id); $this->site->setMemberProfilePicture(); $json['success'] = 'success'; } else { $json['success'] = 'failed'; } header('Content-Type: application/json'); echo json_encode($json); } } ?> |
Step 4: Create a view file index
Create a view file named “index.php” inside “application/views/crop” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<?php $this->load->view('templates/header'); ?> <link rel="stylesheet" href="<?php print HTTP_CROP_PATH; ?>css/cropper.css"> <style type="text/css"> .edit-pen{ position: absolute; color: #01579B; background: #fff; padding: 5px; box-shadow: 1px 1px 1px 1px #eee; border-radius: 17px; right: 329px; bottom: 2px; border: 1px solid #f1f1f1; } </style> <div class="row page-content"> <div class="col-lg-12 text-right"> <div class="row"> <div class="col-lg-12 col-sm-12"> <div class="card hovercard"> <div class="cardheader"> <div class="avatar" style="top: 11px;"> <?php if(!empty($userInfo['url'])) { $url = HTTP_USER_PROFILE_THUMB_PATH.$userInfo['url']; } else { $url = HTTP_IMAGES_PATH .'user-default.jpg'; } ?> <img src="<?php print $url;?>" alt="jaeeme" title="jaeeme" data-toggle="modal" data-target="#avatar-modal" id="render-avatar" class="circular-fix has-shadow border marg-top10" data-ussuid="<?php print base64_encode(1);?>" data-backdrop="static" data-keyboard="false" data-upltype="avatar" style="width:150px; height:150px; max-width: 150px; max-height: 150px;"> <i class="fa fa-pencil edit-pen"></i> </div> </div> <div class="card-body info"> <div class="title"> <a href="<?php print site_url() ?>profile"><?php print $userInfo['full_name']; ?></a> </div> <div class="desc"> <a target="_blank" rel="noopener"> rel="noopener noreferrer> <?php PRINT APPLICATION_NAME; ?></a> </div> <div class="desc"><?php print $userInfo['email']; ?>, <?php print $userInfo['contact_no']; ?></div> <div class="desc"><?php print $userInfo['address']; ?></div> </div> <div class="card-footer bottom"> <a class="btn btn-primary btn-twitter btn-sm" href="#"> <i class="fa fa-twitter"></i> </a> <a class="btn btn-danger btn-sm" rel="publisher" href="#"> <i class="fa fa-google-plus"></i> </a> <a class="btn btn-primary btn-sm" rel="publisher" href="#"> <i class="fa fa-facebook"></i> </a> </div> </div> </div> </div> </div> </div> <?php $this->load->view('templates/footer'); $this->load->view('crop/profileAvatar'); ?> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-filestyle/2.1.0/bootstrap-filestyle.js"></script> <script src="<?php print HTTP_CROP_PATH; ?>js/cropper.js"></script> <script src="<?php print HTTP_CROP_PATH; ?>js/main.js"></script> |
Step 5: Create a file main.js
Create a view file named “main.php” inside “assets/crop/js” folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node / CommonJS factory(require('jquery')); } else { // Browser globals. factory(jQuery); } })(function ($) { 'use strict'; var console = window.console || { log: function () {} }; function CropAvatar($element) { this.$container = $element; this.$avatarView = this.$container.find('.avatar-view'); this.$avatar = this.$avatarView.find('img'); this.$avatarModal = this.$container.find('#avatar-modal'); this.$loading = this.$container.find('.loading'); this.$avatarForm = this.$avatarModal.find('.avatar-form'); this.$avatarUpload = this.$avatarForm.find('.avatar-upload'); this.$avatarSrc = this.$avatarForm.find('.avatar-src'); this.$avatarData = this.$avatarForm.find('.avatar-data'); this.$avatarInput = this.$avatarForm.find('.avatar-input'); this.$avatarSave = this.$avatarForm.find('.avatar-save'); this.$avatarBtns = this.$avatarForm.find('button.avatar-btns'); this.$avatarWrapper = this.$avatarModal.find('.avatar-wrapper'); this.$avatarPreview = this.$avatarModal.find('.avatar-preview'); this.init(); } CropAvatar.prototype = { constructor: CropAvatar, support: { fileList: !!$('<input type="file">').prop('files'), blobURLs: !!window.URL && URL.createObjectURL, formData: !!window.FormData }, init: function () { this.support.datauri = this.support.fileList && this.support.blobURLs; if (!this.support.formData) { this.initIframe(); } this.initTooltip(); this.initModal(); this.addListener(); }, addListener: function () { this.$avatarView.on('click', $.proxy(this.click, this)); this.$avatarInput.on('change', $.proxy(this.change, this)); this.$avatarForm.on('submit', $.proxy(this.submit, this)); this.$avatarBtns.on('click', $.proxy(this.rotate, this)); }, initTooltip: function () { this.$avatarView.tooltip({ placement: 'bottom' }); }, initModal: function () { this.$avatarModal.modal({ show: false }); }, initPreview: function () { var url = this.$avatar.attr('src'); this.$avatarPreview.html('<img src="' + url + '">'); }, initIframe: function () { var target = 'upload-iframe-' + (new Date()).getTime(); var $iframe = $('<iframe>').attr({ name: target, src: '' }); var _this = this; // Ready ifrmae $iframe.one('load', function () { // respond response $iframe.on('load', function () { var data; try { data = $(this).contents().find('body').text(); } catch (e) { console.log(e.message); } if (data) { try { data = $.parseJSON(data); } catch (e) { console.log(e.message); } _this.submitDone(data); } else { _this.submitFail('Image upload failed!'); } _this.submitEnd(); }); }); this.$iframe = $iframe; this.$avatarForm.attr('target', target).after($iframe.hide()); }, click: function () { this.$avatarModal.modal('show'); this.initPreview(); }, change: function () { var files; var file; if (this.support.datauri) { files = this.$avatarInput.prop('files'); if (files.length > 0) { file = files[0]; if (this.isImageFile(file)) { if (this.url) { URL.revokeObjectURL(this.url); // Revoke the old one } this.url = URL.createObjectURL(file); this.startCropper(); } } } else { file = this.$avatarInput.val(); if (this.isImageFile(file)) { this.syncUpload(); } } }, submit: function () { if (!this.$avatarSrc.val() && !this.$avatarInput.val()) { return false; } if (this.support.formData) { this.ajaxUpload(); return false; } }, rotate: function (e) { var data; if (this.active) { data = $(e.target).data(); if (data.method) { this.$img.cropper(data.method, data.option); } } }, isImageFile: function (file) { if (file.type) { return /^image\/\w+$/.test(file.type); } else { return /\.(jpg|jpeg|png|gif)$/.test(file); } }, startCropper: function () { var _this = this; if (this.active) { this.$img.cropper('replace', this.url); } else { this.$img = $('<img src="' + this.url + '">'); this.$avatarWrapper.empty().html(this.$img); this.$img.cropper({ aspectRatio: 1, preview: this.$avatarPreview.selector, crop: function (e) { var json = [ '{"x":' + e.x, '"y":' + e.y, '"height":' + e.height, '"width":' + e.width, '"rotate":' + e.rotate + '}' ].join(); _this.$avatarData.val(json); } }); this.active = true; } this.$avatarModal.one('hidden.bs.modal', function () { _this.$avatarPreview.empty(); _this.stopCropper(); }); }, stopCropper: function () { if (this.active) { this.$img.cropper('destroy'); this.$img.remove(); this.active = false; } }, ajaxUpload: function () { var url = this.$avatarForm.attr('action'); var data = new FormData(this.$avatarForm[0]); var _this = this; $.ajax(url, { type: 'post', data: data, dataType: 'json', processData: false, contentType: false, beforeSend: function () { _this.submitStart(); jQuery('button.avatar-save').button('loading'); }, success: function (data) { _this.submitDone(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { _this.submitFail(textStatus || errorThrown); }, complete: function () { _this.submitEnd(); jQuery('button.avatar-save').button('reset'); } }); }, syncUpload: function () { this.$avatarSave.click(); }, submitStart: function () { this.$loading.fadeIn(); }, submitDone: function (data) { if ($.isPlainObject(data) && data.state === 200) { if (data.result) { // ajax funtionality save image path in database $.ajax({ url: baseurl + "crop/uploadCropImg", type: 'post', data: {image_url:data.thumb, member_id: data.ussid, upltype:data.upltype, urlPath:data.urlPath}, dataType: 'json', beforeSend: function () {}, complete: function () {}, success: function (json) {} }); jQuery('img#render-avatar').attr('src', data.urlPath+data.thumb); jQuery('input#profile-avatar-url').val(data.thumb); //this.$avatar.attr('src', url+'assets/uploads/_thumb/'+data.thumb); this.url = data.result; if (this.support.datauri || this.uploaded) { this.uploaded = false; this.cropDone(); } else { this.uploaded = true; this.$avatarSrc.val(this.url); this.startCropper(); } this.$avatarInput.val(''); } else if (data.message) { this.alert(data.message); } } else { this.alert('Failed to response'); } }, submitFail: function (msg) { this.alert(msg); }, submitEnd: function () { this.$loading.fadeOut(); }, cropDone: function () { this.$avatarForm.get(0).reset(); //this.$avatar.attr('src', this.url); this.stopCropper(); this.$avatarModal.modal('hide'); }, alert: function (msg) { var $alert = [ '<div class="alert alert-danger avatar-alert alert-dismissable">', '<button type="button" class="close" data-dismiss="alert">×</button>', msg, '</div>' ].join(''); this.$avatarUpload.after($alert); } }; $(function () { return new CropAvatar($('#crop-avatar')); }); // render image jQuery(document).on('click','img#render-avatar', function(){ jQuery('input#ussmid').val(jQuery(this).data('ussuid')); jQuery('input#upltypeid').val(jQuery(this).data('upltype')); }); }); |
Step 7: Open file constants
Open “application/config/routes.php” file and add code like as bellow:
1 2 3 4 5 |
<?php // routes $route['default_controller'] = 'crop/index'; $route['upload/crop'] = "crop/upload"; ?> |