Resize Image Without Stretching in Codeigniter


In this article I’m going to show you the mathematics and logics of resizing an image to a different width and height without squeezing or stretching the original image. If the source image has a different aspect ratio than the destination image, the source image will be cropped.

You may also like

Resize image without stretching in codeigniter

I’m not going to explain about uploading an image as I’m focusing only resizing an image here. In this article the step or module I’m going to explain you have to apply this module after uploading an image, so let’s get started.

paste bellow function in your controller

public function resize_image($image_data){
    $w = $image_data['image_width']; // original image's width
    $h = $image_data['image_height']; // original images's height

    $n_w = 273; // destination image's width
    $n_h = 246; // destination image's height

    $source_ratio = $w / $h;
    $new_ratio = $n_w / $n_h;
    if($source_ratio != $new_ratio){

        $config['image_library'] = 'gd2';
        $config['source_image'] = './uploads/uploaded_image.jpg';
        $config['maintain_ratio'] = FALSE;
        if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1))){
            $config['width'] = $w;
            $config['height'] = round($w/$new_ratio);
            $config['y_axis'] = round(($h - $config['height'])/2);
            $config['x_axis'] = 0;

        } else {

            $config['width'] = round($h * $new_ratio);
            $config['height'] = $h;
            $size_config['x_axis'] = round(($w - $config['width'])/2);
            $size_config['y_axis'] = 0;


    $config['image_library'] = 'gd2';
    $config['source_image'] = './uploads/uploaded_image.jpg';
    $config['new_image'] = './uploads/new/resized_image.jpg';
    $config['maintain_ratio'] = TRUE;
    $config['width'] = $n_w;
    $config['height'] = $n_h;

    if (!$this->image_lib->resize()){

        echo $this->image_lib->display_errors();

    } else {

        echo "done";


after uploading an image you’ve to call above function along with uploaded image data (array)

    $image_data = $this->upload->data();

that’s all you have to do…

if you find this article helpful please share it with your friend,

Leave a Reply

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