Mehur Mehur - 1 month ago 16
PHP Question

How to crop image after upload and get image url?

I am using codeigniter 3.1 .

I want to crop image after upload but the crop not working.

After crop how to get the image url ?

if ($_FILES['upload']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => $this->upload_path,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
));

$data = $this->upload->data();
$image = $data['file_name'];

$this->load->library('image_lib');
$this->image_lib->initialize(array(
"source_image" => $data,
"new_image" => $this->upload_path. $image,
"x_axis" => 300,
"y_axis" => 300
));

$data = $this->upload->data();
$image = $data['file_name'];

//Get full path of image

}

Answer

Use these functions in your model

<?php 
 class Image_model extends CI_Model {
public function __construct()   {
    parent::__construct();
    $this->load->helper('url');
    $this->load->library('upload');
    $this->load->library('image_lib');
}

public function do_resize($filename)
{

    $source_path =  'uploads/' . $filename;
    $target_path =  'uploads/thumb/'.$filename;

    $config_manip = array(

        'image_library' => 'gd2',
        'source_image' => $source_path,
        'new_image' => $target_path,
        'maintain_ratio' => TRUE,
        'width' => 300,
        'height' => 300
    );
    $this->image_lib->initialize($config_manip);
    $this->load->library('image_lib', $config_manip);


    if (!$this->image_lib->resize()) {
        echo $this->image_lib->display_errors();
        die();
    }
}

public function img_upload()
{
    $config = array(
        'upload_path' => "uploads",
        'allowed_types' => "*",
        'overwrite' => TRUE,
        'max_size' => "5048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
        'max_height' => "3000",
        'max_width' => "3000"
    );
    $this->upload->initialize($config);
    $this->load->library('upload', $config);

    if($this->upload->do_upload('myFile')) { //<input type="file" name="myFile" />
        $response   =    array('upload_data' => $this->upload->data());
        $this->do_resize($response['upload_data']['file_name']);
        //return $response;
    }
    else{
        $error              =   array('error'=>$this->upload->display_errors());
        print_r($error);die(); 

    }
 }
}

Call this function in your controller like this

if(isset($_FILES)){

            $config                 =   $this->image_model->img_upload();
            $file_data              =   $this->upload->data();
            $data['img']            =   $file_data['file_name'];
        }