How to crop an image to the center when uploading it

Asked

Viewed 6,948 times

9

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

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

So I need to ensure that all images that will be shown have square sizes, ie 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 cropping has to be in the center of the image. EX:

Imagem usada no upload, sem o recorte

Imagem usada no upload com o recorte

As you can see, the image was cropped in the center, and now it has identical Height and Width.

  • 3

    I don’t know if this automatic is the best... Not all images have the focus in the center.

  • 1

    I searched the internet and using jcrop, so when you upload the user can choose which point of the image he wants to display. That way I solve both problems. One on the image if of different size and the other on the focus of the image, so the user himself decided which part of the image is the best

3 answers

8

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>

inserir a descrição da imagem aqui


Page that receives data for clipping: (crop.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';
    }

inserir a descrição da imagem aqui

6


Well, guys, the question was how to cut an image in the center by uploading it. I researched on the Internet and ended up changing my mind and using JCROP, but the question itself had not been answered, so I searched the subject on the Internet and ended up finding a script that solved my question. It’s not my script, but I did a little minor editing to better fit my initial goal.

Here is 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);}


  ?>

5

You can do this with cutting in the server slime, I use imagine has a very interesting OO approach to image manipulation.

Installation

Add the following dependency to your Composer.json file:

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

Example of use

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'])
;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.