How to crop an image to the center when uploading it

In the project here I want to display the images in a square Div of dynamic dimension where its maximum size is 240 x 240.

Assuming that a user uploads an image with rectangular dimension (ex: 500 x 280), this same div is "disfigured" since its height is auto, so the height is proportional to the width. And my goal and leave all div with square format.

So I need to ensure that all images that will be displayed have square dimensions, that is, 200x200, 300x300, or any other size as long as it is square.

In my view an easy way to do this is by cropping the image at the time of upload. And preferably the cutout has to be in the center of the image. EX:

Image used in upload, without cropping

Image used in upload with cropping

As can be seen, the image has been cropped to the center, and now it has identical height and width.

Author: bfavaretto, 2014-08-31

3 answers

Download the package JCrop and make two pages like this:

home: (crop.php)

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Arquivo</title>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.12/js/jquery.Jcrop.min.js"></script>
<script language="Javascript"> 
    $(function(){ 
        $('#ImagemCrop').Jcrop({
            aspectRatio: 1,
            onSelect: UpdateCrop,
            setSelect: [0, 0, 200, 200],
        });

    }); 
    function UpdateCrop(c)
    {
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
        $("#altura").html("Altura:" + c.h);
        $("#largura").html("Largura:" + c.w);
    };  
</script>
</head>
<body>
    <div id="altura">Altura:</div>
    <div id="largura">Largura:</div>
    <form action="recorte.php" method="post">
        <input type="hidden" id="x" name="x" />
        <input type="hidden" id="y" name="y" />
        <input type="hidden" id="w" name="w" />
        <input type="hidden" id="h" name="h" />
        <input type="hidden" id="imagem" name="imagem" value="img/1.jpg" />
        <input type="submit" value="Recortar Imagem" />
    </form>
    <img src="img/1.jpg" id="ImagemCrop" />
</body>
</html>

insert the description of the image here


page that receives the data for clipping: (clipping.php)

<?php
    if (isset($_POST['imagem']) && 
        isset($_POST['x']) && 
        isset($_POST['y']) && 
        isset($_POST['w']) && 
        isset($_POST['h']))
    {
        $targ_w = $_POST['w'];
        $targ_h = $_POST['h'];
        $jpeg_quality = 90;

        $src = $_POST['imagem'];
        $img_r = imagecreatefromjpeg($src);
        $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

        imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
        $targ_w,$targ_h,$_POST['w'],$_POST['h']);

        header('Content-type: image/jpeg');
        imagejpeg($dst_r,null,$jpeg_quality);    
    } else {
        echo 'error';
    }

insert the description of the image here

 8
Author: Maria, 2014-08-31 14:36:55

Good Guys, the question was about how to crop an image to the center when uploading it. I searched on the internet and ended up changing my mind and using JCROP, but the question in itself had not been answered, I then searched on the internet and ended up finding a script that solved my question. The script is not mine, but I made a few small edits to better adapt to my initial goal.

Here's the script:

  <form action="" method="post" enctype="multipart/form-data">
  <input name="img" type="file" />
  <input type="submit" name="cadastrar" />
  </form>


  <?php
  if(isset($_POST['cadastrar'])){ 
  $img  = $_FILES['img'];
  $name =$img['name'];
  $tmp  =$img['tmp_name'];
  $ext  =end(explode('.',$name));

  $pasta        ='NOMEDAPASTA/'; //Pasta onde a imagem será salva

  $permiti  =array('jpg', 'jpeg', 'png');
  $name = uniqid().'.'.$ext; $uid = uniqid();

  $upload   = move_uploaded_file($tmp, $pasta.'/'.$name);}; //Faz o upload da imagem para o servidor

  if($upload){
  function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 60){
  $imgsize = getimagesize($source_file);
  $width = $imgsize[0];
  $height = $imgsize[1];
  $mime = $imgsize['mime'];
  //resize and crop image by center
  switch($mime){
  case 'image/gif':
  $image_create = "imagecreatefromgif";
  $image = "imagegif";
  break;
  //resize and crop image by center
  case 'image/png':
  $image_create = "imagecreatefrompng";
  $image = "imagepng";
  $quality = 6;
  break;
  //resize and crop image by center
  case 'image/jpeg':
  $image_create = "imagecreatefromjpeg";
  $image = "imagejpeg";
  $quality = 60;
  break;
  default:
  return false;
  break;
  }
  $dst_img = imagecreatetruecolor($max_width, $max_height);
  $src_img = $image_create($source_file);
  $width_new = $height * $max_width / $max_height;
  $height_new = $width * $max_height / $max_width;
  if($width_new > $width){
  $h_point = (($height - $height_new) / 2);
  imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
  }else{
  $w_point = (($width - $width_new) / 2);
  imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
  }
  $image($dst_img, $dst_dir, $quality);
  if($dst_img)imagedestroy($dst_img);
  if($src_img)imagedestroy($src_img);
  }

  //Tamanho da Imagem final
  resize_crop_image(300, 300, $pasta.'/'.$name, $pasta.'/'.$name);}


  ?>
 6
Author: ivan veloso, 2014-09-01 02:11:58

You can do this with slicing in server sludge, I use imagine has a very interesting Oo approach to image manipulation.

Installation

Add in your composer file.json the following dependency:

"require": {
    "imagine/imagine": "dev-master"
},

Usage example

require_once './vendor/autoload.php';

$imagine = new Imagine\Gd\Imagine();

$size = new Imagine\Image\Box(200, 200);

$mode = Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND;

$imagine->open($_FILES['file']['tmp_name'])
        ->thumbnail($size, $mode)
        ->save(__DIR__ . '/upload/' . $_FILES['file']['name'])
;
 5
Author: Fábio Lemos Elizandro, 2014-09-01 12:24:35