CodeIgniter Resize and Crop Image To Fit Container Div Example

When a user uploads an image to be displayed on a webpage, we need to make sure that the image has the following:

a) fits correctly into a fixed height and width container without overflowing or any blank space.
b) displays in full image resolution (without shrinking or expanding image using CSS width and height).
c) image displayed is not skewed or distorted and keeping image ratio.

References to CodeIgniter libraries:
http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
http://ellislab.com/codeigniter/user-guide/libraries/image_lib.html

By using CodeIgniter framework, I manage to achieve the above.

Workflow:

1) Upload the raw image using standard file upload form. Upload handling backend:

$config['upload_path'] = './data/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'product.png';
$config['overwrite'] = TRUE;
$config['max_size']	= '0';
$config['max_width']  = '0';
$config['max_height']  = '0';	

$this->load->library('upload', $config);

if(!is_dir($config['upload_path'])){
   	mkdir($config['upload_path'], 0755, TRUE);
}

if (!$this->upload->do_upload("file_upload")){ //Upload file
			redirect("errorhandler"); //If error, redirect to an error page
		}else{
  ...

2) Next, we will do image resizing. Set the configuration as below:

   
$upload_data = $this->upload->data();
$image_config["image_library"] = "gd2";
$image_config["source_image"] = $upload_data["full_path"];
$image_config['create_thumb'] = FALSE;
$image_config['maintain_ratio'] = TRUE;
$image_config['new_image'] = $upload_data["file_path"] . 'product.png';
$image_config['quality'] = "100%";
$image_config['width'] = 231;
$image_config['height'] = 154;
$dim = (intval($upload_data["image_width"]) / intval($upload_data["image_height"])) - ($image_config['width'] / $image_config['height']);
$image_config['master_dim'] = ($dim > 0)? "height" : "width";

$this->load->library('image_lib');
$this->image_lib->initialize($image_config);

if(!$this->image_lib->resize()){ //Resize image
	redirect("errorhandler"); //If error, redirect to an error page
}else{
     ...

Explanation: “maintain_ratio” parameter is set to TRUE. From code above, the container size used for this example is (231px × 154px) (W × H).

Before resizing, we need to know whether to use width or height edge as the hard-value. After the original image has been resized, either the original image width’s edge or the height’s edge will be the same as the container width’s edge or the height’s edge respectively. The one that is same has the hard-value length. We determine this using calculation below:

Ratio = (Original Image Width / Original Image Height) – (Container Width / Container Height)

If the ratio > 0, then original image has longer width than container width. Hence, we take the height as hard-value as it has shorter height ratio.
If the ratio < 0, then original image has longer height than container height. Hence, we take width as hard-value as it has shorter width ratio.
if ratio = 0, both width or height can be the hard-value.

The purpose of doing this is to ensure resized image is able to fill the container completely without white spaces.

See visual description below:

Compare

Above shows container and image with different sizes.

Overlap

To determine which edge to be used as hard-value, we overlap the container and the original image. We will shrink the original image while keeping its ratio. The arrow indicates the shrinking direction. The edge of the image that first matches the container edge length will be the hard-value.

Image_07

When either one of the edge matches the container edge, we stop resizing. The orange box represents the final image.

3) After resizing the image, we will crop it to fit into the container. Set the configurations as below:

$image_config['image_library'] = 'gd2';
$image_config['source_image'] = $upload_data["file_path"] . 'product.png';
$image_config['new_image'] = $upload_data["file_path"] . 'product.png';
$image_config['quality'] = "100%";
$image_config['maintain_ratio'] = FALSE;
$image_config['width'] = 231;
$image_config['height'] = 154;
$image_config['x_axis'] = '0';
$image_config['y_axis'] = '0';

$this->image_lib->clear();
$this->image_lib->initialize($image_config); 

if (!$this->image_lib->crop()){
       	redirect("errorhandler"); //If error, redirect to an error page
}else{
	redirect("successpage");
}

Note that ‘x_axis‘ and ‘y_axis‘ are set to 0. We don’t need to crop away any parts. We will use width and height parameters to generate the image part that we need.

Final

Image resizing and cropping to fit into container is done.

14 thoughts on “CodeIgniter Resize and Crop Image To Fit Container Div Example

  1. Lucas

    Great tut! I just have one question. How can I do to move the crop? I want the crop in the middle of the image. Not at the top or the bottom.

    How can I do that?

    Thanks in advance!

    Reply
    1. admin Post author

      From the configuration $image_config, set parameter for “x_axis” and “y_axis”. See below:

      $image_config[‘x_axis’] = ‘0’; //Sets the X coordinate in pixels for image cropping. For example, a setting of 30 will crop an image 30 pixels from the left.
      $image_config[‘y_axis’] = ‘0’; //Sets the Y coordinate in pixels for image cropping. For example, a setting of 30 will crop an image 30 pixels from the top.

      For your case,
      ((“before cropped” image width) – (container width)) / 2 = x_axis pixels
      ((“before cropped” image height) – (container height)) / 2 = y_axis pixels

      In other words, to get the center location, we remove half of the image that is outside the container.

      Reply
      1. Lucas

        Thanks a lot for your help! But I’ve one more issue with this. Why I’m getting an all black image? And not the current image?

        Reply
        1. admin Post author

          Try experimenting a bit. Change x_axis and y_axis with different small values. What i referring is $image_config for the “image cropping” part point (3).

          $image_config[‘x_axis’] = 10;
          $image_config[‘y_axis’] = 10;

          Black image probably caused by over-cropping.

          Reply
          1. admin Post author

            I guessed you haven’t get the “before-cropped” image size. This image is after resizing but before cropping.

            Try this:

            $vals = @getimagesize($upload_data[“file_path”] . ‘product.png’);
            $width = $vals[‘0’];
            $height = $vals[‘1’];

            $image_config[‘x_axis’] = ($width – 231)/2;
            $image_config[‘y_axis’] = ($height – 154)/2;

            *Note “231” and “154” are just samples. Modify according to your container size.

          2. Lucas

            Well thanks a lot for your help. I figured it out reading your last entry and something that I’ve found on the internet.

            Something that’s not explained in the CodeIgniter guide is that you need 4 measurements to crop the image : where to start vertically (y_axis), where to start horizontally (x_axis), where to end vertically (height) and where to end horizontally (width)

            So with that in mind I realised what my problem was:

            $image_config[‘x_axis’] = ( $imageSize[‘width’] – $this->config[‘width’] ) / 2; // where to start horizontally
            $image_config[‘y_axis’] = ( $imageSize[‘height’] – $this->config[‘height’] ) / 2; // where to start vertically
            $image_config[‘width’] = $this->config[‘width’]; // where to end vertically
            $image_config[‘height’]= $this->config[‘height’]; // where to end horizontally

            $this->config contains the size that I need to crop. So that do the work.

            Thanks admin for all your help, without your post I’d not have been able to solve this issue.

  2. Pingback: CodeIgniter Resize and Crop Image To Fit Container Div Example - PHP Blog Spot

  3. razik

    how can i resize image for this….
    query(“select * from register where email=’$email'”,4);
    if(count($query1) > 0)
    {
    echo “”;
    echo “alert(’email already exist’)”;
    echo “”;
    }
    $query2=$dbobj->action_query(“INSERT into register(firstname,lastname,email,password,dateofbirth,gender,phonenumber,address,photo)VALUES(‘$firstname’,’$lastname’,’$email’,’$password’,’$dob’,’$gender’,’$phonenumber’,’$address’,’$photo’)”,1);
    move_uploaded_file($_FILES[‘photo’][‘tmp_name’],$target_file);
    if($query2==true)
    {
    // header(“location: adduser.php”);

    $regis=’success’;

    }
    }
    ?>

    Reply

Leave a Reply to nishi Cancel reply

Your email address will not be published. Required fields are marked *


three + 8 =