Pretendo mostrar rapidamente como fazer um crop (cortar)de imagens usando CodeIgniter e o plugin Croppic.
Este exemplo foi desenvolvido em 29/10/15, usando XAMPP for Windows 5.6.12, chrome V. 46.0.2490.80 m, PHP V.5.6.12, CodeIgniter 3.0.2.
Vou pressupor que você já conhece o básico de CodeIgniter, de qualquer forma vou colocar aqui o link para você baixar o mesmo, e também o link para o plugin.
Baixar CodeIgniter.
Baixar plugin Croppic.
A partir deste momento passo a chamar o CodeIgniter simplesmente de CI.
Crie na pasta do htdocs do xampp uma pasta chamada "crop" ou outro nome qualquer de sua preferencia.
Dentro desta pasta jogue os arquivos do CI, de tal forma que fique como a imagem abaixo.
Após crie um arquivo .htaccess na raiz da pasta crop, com as seguintes linha:
Imagem 01 | |
---|---|
|
Deixe somente os arquivos e pastas que aparecem na imagem, os demais podem ser excluídos. |
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [PT,L]
Estas instruções são para não poder acessar os arquivos diretamente e também para possibilitar o uso de URL amigável que é o que nos interessa neste momento.
Bom apos baixar e descompactar o plugin croppic, copie também as pastas assets e temp, devendo o resultado ser como a imagem 02.
Imagem 02 | |
---|---|
|
Na pasta C:\xampp\htdocs\crop\application\config, abra o arquivo autoload.php, no autoload-helper coloque $autoload['helper'] = array('url'); No arquivo routes.php acerte a rota default $route['default_controller'] = 'home';
Estas mudanças são necessárias para que ele interprete corretamente as URL's e para que assuma home como seu controller inicial.
No CI, crie um crontroller chamado home.
dentro deste controler coloque a codificação abaixo (home.php).
Home |
---|
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends CI_Controller { public function index() { $this->load->view('imagem'); } } |
Agora crie na pasta view o arquivo imagem.php e dentro dele coloque a programação abaixo:
imagem | |
---|---|
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="<?php echo base_url() . 'assets/img/favicon.png' ?>"> <title>CodeIgniter e Croppic</title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url() . 'assets/css/bootstrap.css" rel="stylesheet' ?>"> <!-- Custom styles for this template --> <link href="<?php echo base_url() . 'assets/css/main.css" rel="stylesheet' ?>"> <link href="<?php echo base_url() . 'assets/css/croppic.css" rel="stylesheet' ?>"> <!-- Fonts from Google Fonts --> <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&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="row mt centered"> <div class="row mt "> <div class="col-lg-4 "> <h4 class="centered"> OUTPUT </h4> <p class="centered">( display url after cropping )</p> <div id="cropContaineroutput"></div> <input type="text" id="cropOutput" style="width:100%; padding:5px 4%; margin:20px auto; display:block; border: 1px solid #CCC;" /> </div> </div> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <!-- <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> --> <script src=" https://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="<?php echo base_url() . 'assets/js/bootstrap.min.js' ?>"></script> <script src="<?php echo base_url() . 'assets/js/jquery.mousewheel.min.js' ?>"></script> <script src="<?php echo base_url() . 'assets/js/croppic.min.js' ?>"></script> <script src="<?php echo base_url() . 'assets/js/main.js' ?>"></script> <script> var croppicContaineroutputOptions = { uploadUrl: '<?php echo base_url() . "home/img_save_to_file" ?>', cropUrl: '<?php echo base_url() . "home/img_crop_to_file" ?>', outputUrlId: 'cropOutput', modal: false, loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> ', onBeforeImgUpload: function () { console.log('onBeforeImgUpload')}, onAfterImgUpload: function () {console.log('onAfterImgUpload')}, onImgDrag: function () {console.log('onImgDrag')}, onImgZoom: function () {console.log('onImgZoom')}, onBeforeImgCrop: function () {console.log('onBeforeImgCrop')}, onAfterImgCrop: function () {console.log('onAfterImgCrop')}, onReset: function () {console.log('onReset')}, onError: function (errormessage) {console.log('onError:' + errormessage)} } var cropContaineroutput = new Croppic('cropContaineroutput', croppicContaineroutputOptions); </script> </body> </html> |
Para criar o arquivo a cima, copie o conteúdo do arquivo index.html que esta no raiz do pacote do croppic. Faça os ajuste para ficar conforme o código acima, neste momento você pode optar por deixar mais funcionalidades do que eu deixei para isso preserve o que interessa para você. Basta que depois ajuste o código conforme as partes destacadas em vermelho.
Tambem no pacote croppic você encontrar dois programas PHP, abra este dois programas e copie seu conteudo para o nosso controller home, de forma que cada programa passe a ser um metodo, conforme abaixo.
Home (completo) |
---|
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Home extends CI_Controller { public function index() { $this->load->view('imagem'); } public function img_crop_to_file() { $imgUrl = $_POST['imgUrl']; // original sizes $imgInitW = $_POST['imgInitW']; $imgInitH = $_POST['imgInitH']; // resized sizes $imgW = $_POST['imgW']; $imgH = $_POST['imgH']; // offsets $imgY1 = $_POST['imgY1']; $imgX1 = $_POST['imgX1']; // crop box $cropW = $_POST['cropW']; $cropH = $_POST['cropH']; // rotation angle $angle = $_POST['rotation']; $jpeg_quality = 100; $output_filename = "temp/croppedImg_".rand(); // uncomment line below to save the cropped image in the same location as the original image. //$output_filename = dirname($imgUrl). "/croppedImg_".rand(); $what = getimagesize($imgUrl); switch(strtolower($what['mime'])) { case 'image/png': $img_r = imagecreatefrompng($imgUrl); $source_image = imagecreatefrompng($imgUrl); $type = '.png'; break; case 'image/jpeg': $img_r = imagecreatefromjpeg($imgUrl); $source_image = imagecreatefromjpeg($imgUrl); error_log("jpg"); $type = '.jpeg'; break; case 'image/gif': $img_r = imagecreatefromgif($imgUrl); $source_image = imagecreatefromgif($imgUrl); $type = '.gif'; break; default: die('image type not supported'); } //Check write Access to Directory if(!is_writable(dirname($output_filename))){ $response = Array( "status" => 'error', "message" => 'Can`t write cropped File' ); }else{ // resize the original image to size of editor $resizedImage = imagecreatetruecolor($imgW, $imgH); imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, $imgH, $imgInitW, $imgInitH); // rotate the rezized image $rotated_image = imagerotate($resizedImage, -$angle, 0); // find new width & height of rotated image $rotated_width = imagesx($rotated_image); $rotated_height = imagesy($rotated_image); // diff between rotated & original sizes $dx = $rotated_width - $imgW; $dy = $rotated_height - $imgH; // crop rotated image to fit into original rezized rectangle $cropped_rotated_image = imagecreatetruecolor($imgW, $imgH); imagecolortransparent($cropped_rotated_image, imagecolorallocate($cropped_rotated_image, 0, 0, 0)); imagecopyresampled($cropped_rotated_image, $rotated_image, 0, 0, $dx / 2, $dy / 2, $imgW, $imgH, $imgW, $imgH); // crop image into selected area $final_image = imagecreatetruecolor($cropW, $cropH); imagecolortransparent($final_image, imagecolorallocate($final_image, 0, 0, 0)); imagecopyresampled($final_image, $cropped_rotated_image, 0, 0, $imgX1, $imgY1, $cropW, $cropH, $cropW, $cropH); // finally output png image //imagepng($final_image, $output_filename.$type, $png_quality); imagejpeg($final_image, $output_filename.$type, $jpeg_quality); $response = Array( "status" => 'success', "url" => base_url(). $output_filename.$type ); } print json_encode($response); } public function img_save_to_file(){ /* * !!! THIS IS JUST AN EXAMPLE !!!, PLEASE USE ImageMagick or some other quality image processing libraries */ $imagePath = "temp/"; $allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG"); $temp = explode(".", $_FILES["img"]["name"]); $extension = end($temp); //Check write Access to Directory if(!is_writable($imagePath)){ $response = Array( "status" => 'error', "message" => $imagePath ); print json_encode($response); return; } if ( in_array($extension, $allowedExts)) { if ($_FILES["img"]["error"] > 0) { $response = array( "status" => 'error', "message" => 'ERROR Return Code: '. $_FILES["img"]["error"], ); } else { $filename = $_FILES["img"]["tmp_name"]; list($width, $height) = getimagesize( $filename ); move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]); $response = array( "status" => 'success', "url" => base_url(). $imagePath.$_FILES["img"]["name"], "width" => $width, "height" => $height ); } } else { $response = array( "status" => 'error', "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini', ); } print json_encode($response); } } /* Location: ./application/controllers/home.php */ |
Veja no código acima as partes destacadas em vermelho.
Senhores, o resultado final, quando executado o site, deve ser uma tela igual a tela abaixo (salvo, obviamente se você deixou mais funcionalidades).
Na sequencia.
Imagem 03, 04 e 05 |
---|
|
Link do projeto.
Aqui.
Um abraço,
Estou em um novo projeto pessoal, desenvolvimento de site/crm para imobiliárias e corretores, usando CodeIgniter, caso você tenha interesse em conhecer acesse o exemplo em www.minhacasa.floripa.br
Estou em um novo projeto pessoal, desenvolvimento de site/crm para imobiliárias e corretores, usando CodeIgniter, caso você tenha interesse em conhecer acesse o exemplo em www.minhacasa.floripa.br