Photo upload, Crop and Save using Codeigniter - php

We are working on a social network project based on CI framework. I searched on the web but got confused. How to upload photo, allow user to crop the photo and save it using database so that it could be retrieved at the time of call? I'm using this for profile picture.
On view:
<?php echo form_open_multipart ('index.php/Main/do_upload'); ?>
<table class="table">
<tr>
<td>Title</td>
<td><?php echo form_input('title'); ?></td>
</tr>
<tr>
<td>Image</td>
<td><?php echo form_upload('userfile'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
<?php echo form_close(); ?>
</tr>
</table>
On controller:
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('Material_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}

Use Bluimp Multiple fileupload (https://blueimp.github.io/jQuery-File-Upload) and Croppr (https://fengyuanchen.github.io/cropperjs/) plugins together.
In Bluimp you can get enough code (there is a codeigniter class in their site) to handle file upload in codeigniter.

Please try with cropper js. i have used this and it is very easy and it will full fill your requirement
https://github.com/fengyuanchen/cropper

Create A Image model and paste the code
<?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/thumb_'.$filename;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 150,
'height' => 150
);
$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()) {
$response = array('upload_data' => $this->upload->data());
$this->do_resize($response['upload_data']['file_name']);
}
/*else{
$error = array('error'=>$this->upload->display_errors());
//print_r($error);die();
}*/
}
}
Call this function like this in your controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('image_model');
}
public function add() {
if(isset($_FILES)){
$config = $this->image_model->img_upload();
$file_data = $this->upload->data();
$data['feature_image'] = $file_data['file_name'];
}
$lat_id = $this->your_model->save($data);
}

Related

how to upload path in codeigniter

I am new to CI. Currently I have the following:
$config['upload_path'] = './uploads/';
I just want to know how to update path in codeignitor. I have tried the below code. Is there something I'm doing wrong?
<?php
defined('BASEPATH')`enter code here` OR exit('No direct script access allowed');
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('Upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
From Your code Your file will be uploaded at uploads folder which is in your root directory. $config['upload_path'] = './uploads/'; this is the place where your uploaded files are stored.
You make an directory uploads there where an application folder is .
If you want your current code.
You'll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called uploads and set its file permissions to 777.
By default the upload routine expects the file to come from a form field called userfile.
from file uploading class
Use this library to upload... Its easy to use
http://demo.codesamplez.com/codeigniter/file-upload-demo
View
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" multiple="multiple" />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
{if isset($uploaded_file)}
{foreach from=$uploaded_file key=name item=value}
{$name} : {$value}
<br />
{/foreach}
{/if}
Controller
/**
* the demo for file upload tutorial on codesamplez.com
* #return view
*/
public function file_upload_demo()
{
try
{
if($this->input->post("submit")){
$this->load->library("app/uploader");
$this->uploader->do_upload();
}
return $this->view();
}
catch(Exception $err)
{
log_message("error",$err->getMessage());
return show_error($err->getMessage());
}
}
Component
/**
* Description of uploader
*
* #author Rana
*/
class Uploader {
var $config;
public function __construct() {
$this->ci =& get_instance();
$this->config = array(
'upload_path' => dirname($_SERVER["SCRIPT_FILENAME"])."/files/",
'upload_url' => base_url()."files/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|doc|xml",
'overwrite' => TRUE,
'max_size' => "1000KB",
'max_height' => "768",
'max_width' => "1024"
);
}
public function do_upload(){
$this->remove_dir($this->config["upload_path"], false);
$this->ci->load->library('upload', $this->config);
if($this->ci->upload->do_upload())
{
$this->ci->data['status']->message = "File Uploaded Successfully";
$this->ci->data['status']->success = TRUE;
$this->ci->data["uploaded_file"] = $this->ci->upload->data();
}
else
{
$this->ci->data['status']->message = $this->ci->upload->display_errors();
$this->ci->data['status']->success = FALSE;
}
}
function remove_dir($dir, $DeleteMe) {
if(!$dh = #opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!#unlink($dir.'/'.$obj)) $this->remove_dir($dir.'/'.$obj, true);
}
closedir($dh);
if ($DeleteMe){
#rmdir($dir);
}
}
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image name'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}

How to upload multiple files using codeigniter

I want to upload multiple files using codeigniter.
I have two types of images beforeimage and afterimage. After uploading each image I make entry in database.
I am creating thumbnail as well. To amke it ease I created a separate function, but its not working. this logic works for single image upload.
Html
controller
foreach($_FILES["beforepicture"]['name'] as $key=>$files){
//if(isset($_FILES["beforepicture"]['name']) && $_FILES["beforepicture"]['name'] != ''){
$imagestatus = $this->upload_images($files,'beforepicture');
if(isset($imagestatus['name'])){
$inputdata = array('image' => $imagestatus['name'],
'lead_id' =>$inserted_id,
'user_id'=>$this->session->userdata['userdata']['userid'],
'when'=>'before');
$this->common_model->save('lead_images',$inputdata);
//}
}
}
function upload_images($data = NULL,$inputname=NULL){
if($data){
$this->load->library('image_lib');
// echo '<pre>';
// print_r($_FILES);
$new_name = time().$data;
$config = array(
'upload_path' => getcwd()."/assets/themes/default/avatars/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
// 'max_height' => "768",
//'max_width' => "1024",
'file_name' => $new_name
);
$this->load->library('upload', $config);
$this->upload->initialize($config);
//$this->upload->initialize($config);
if($this->upload->do_upload($inputname))
{
$image_data = $this->upload->data();
//thumb1
$config = array(
'source_image' => $image_data['full_path'], //path to the uploaded image
'new_image' => getcwd()."/assets/themes/default/avatars/thumb", //path to
'maintain_ratio' => true,
'width' => 180,
'height' => 200
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$message = array('name' => $image_data['file_name']);
}else
{
//echo $this->upload->display_errors(); die;
$message = array('failed' => $this->upload->display_errors());
}
return $message;
}
}
I am trying but failed
Try this
<?php
class My_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images);
$this->my_model->upload_image($fileName);
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
}
For more how to upload multiple file in codeigniter try this tutorial:http://w3code.in/2015/09/upload-file-using-codeigniter/
Try this
$files = $_FILES;
$cpt = count($_FILES['beforepicture']['name']);
for($i=0; $i<$cpt; $i++){
$_FILES['beforepicture']['name']= $files['beforepicture']['name'][$i];
$_FILES['beforepicture']['type']= $files['beforepicture']['type'][$i];
$_FILES['beforepicture']['tmp_name']= $files['beforepicture']['tmp_name'][$i];
$_FILES['beforepicture']['error']= $files['beforepicture']['error'][$i];
$_FILES['beforepicture']['size']= $files['beforepicture']['size'][$i];
$imagestatus = $this->upload_images($_FILES["beforepicture"]['name'],'beforepicture');
if(isset($imagestatus['name'])){
$inputdata = array('image' => $imagestatus['name'],
'lead_id' =>$inserted_id,
'user_id'=>$this->session->userdata['userdata']['userid'],
'when'=>'before');
$this->common_model->save('lead_images',$inputdata);
}
}

Thumbnails are not created?

I am trying to create thumbnails original image is been uploaded to upload/large
but not thumbnails are created in upload/thumbs I was using the CodeIgniter Image Manipulation Class and it's not working.Help me to sort out problem
My Controller
var $file_path; //for original image
var $file_path_url; //for thumbnails
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->library('session');
$this->is_login();
$this->load->helper(array('form', 'url'));
$this->load->model('Edit_profile');
//return full path of directory
//Make sure these directory have read and write permission
$this->file_path = realpath(APPPATH . '../upload/large');
$this->file_path_url = realpath(APPPATH.'../upload/thumbs');
// $this->load->model('Insert_article');
}
function upload()
{
//loading image class
$session_data = $this->session->userdata('sessiondata');
$user_id = $session_data['user_id'];
//post image
$img=$this->input->post("filename");
//set preferences
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['upload_path'] = LARGEPATH;
$config['allowed_types'] = 'jpg|png|gif';
$config['max_size'] = '78000';
//load moadel ********
$this->load->model('Edit_profile');
//load upload class library
$this->load->library('upload', $config);
//$this->upload->do_upload('filename') will upload selected file to destiny folder
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('edit_profile', $upload_error);
}
else
{
// case - success
//callback returns an array of data related to the uploaded file like the file name, path, size etc
$upload_data = $this->upload->data();
// call to model function *********
$data['images'] = $this->Edit_profile->insert_new_post($upload_data);
//now creating thumbnails
$config1 = array(
'source_image' => $upload_data['full_path'],
'create_thumb' =>true,
'overwrite' =>false,
'maintain_ratio' =>true,
'new_image' => $this->file_path_url,
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
print_r($config1);
$this->load->library('image_lib');
$this->image_lib->initialize($config1);
$this->image_lib->resize();
//here is the second thumbnail, notice the call for the initialize() function again
//$this->image_lib->initialize($config);
//$this->image_lib->resize();
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . '</strong> was successfully uploaded!</div>';
redirect(base_url("Display_profilepic/index"));
}
}
//Model
function insert_new_post($upload_data)
{
$session_data = $this->session->userdata('sessiondata');
$user_id = $session_data['user_id'];
$filePath = ltrim(LARGEPATH.$upload_data['file_name'],'.');
//print_r(LARGEPATH);
$query = "UPDATE `tbl_usrs` set profile_picture='".$filePath."' where user_id='".$user_id."'";
// $this->db->query($query,array($img));
$arg=array ($upload_data);
if($this->db->query($query,$arg)==true)
{
return true; // if added to database
}else {
return false;
}
}
Please update the new_image value by including the filename also.
$config1 = array(
'image_library'=>'gd2',
'source_image' => $upload_data['full_path'],
'create_thumb' =>true,
'overwrite' =>false,
'maintain_ratio' =>true,
'new_image' => $this->file_path_url.'/'.$upload_data['file_name'], //add slash
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
Try to use the following code
$data = $this->upload->data(); $this->thumb($data);
//Function for creating Thumbnails
function thumb($data) {
$config['image_library'] = 'gd2';
$config['source_image'] = $data['full_path'];
$config['create_thumb'] = TRUE;
// $config['maintain_ratio'] = TRUE;
$config['width'] = 350;
$config['height'] = 250;
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
return true;
}

PHP/Codeigniter - For Loop

Update: Complete Controller
the code below only produces the thumbnail of the first image and successfully uploads all the other images. the problem that i am facing is that the other images do get uploaded but their thumbnails aren't.
<?php
class Upload extends CI_Controller{
function __construct()
{
parent::__construct();
$this->upload_path = realpath(APPPATH . '../uploads');
}
function index()
{
$this->load->view('upload_view', array('error' => ''));
}
function start()
{
// var_dump($_FILES); die();
$config['upload_path'] = $this->upload_path;
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload', $config);
$status = $this->upload->do_multi_upload();
for($i=0;$i<count($status);$i++)
{
$conf = array(
'source_image' => $status[$i]['full_path'],
'new_image' => $this->upload_path . '/thumbs',
'maintain_ratio' => true,
'width' => 200,
'height' => 200
);
$this->load->library('image_lib', $conf);
$this->image_lib->resize();
$this->image_lib->clear();
}
if (!$status)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
var_dump($status);
}
}
}
?>
Load the library prior to starting the loop and without passing parameters to it.
Then, for each of the elements in $status do this:
$this->image_lib->initialize($conf);
... and you don't need to use clear() afterwards.

codeigniter image upload cant grab file name

i have try and try and i just cant get my image to upload.
And i cant grab my image name when i try to echo it out :S.
can you see what im doing wrong.
here is my controller:
<?php
//ADMIN PAGE
if (! defined('BASEPATH')) exit('No direct script access');
class News extends CI_Controller {
//Write post when logged in as admin
function write()
{
//insert image
$config['upload_path'] = APPPATH .'/archive/img/news/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('newsImage');
$file_data = $this->upload->data();
$newsData = array(
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'content' => $this->input->post('content'),
'creater' => $this->session->userdata('username'),
'ip' => $this->session->userdata('ip'),
'imgPath' => $file_data['file_name']
);
echo "<pre>";
//print_r( $this->upload->data());
//print_r($file_data);
//print_r($_FILES);
//print_r($this->input->post());
print_r($newsData);
echo "</pre>";
$this->load->model('admin/news_model');
$this->news_model->insertNews($newsData);
$data['main_content'] = 'admin/write_view';
$this->load->view('template', $data);
}
}
And my view file where i upload my image
<div id="inputStyle">
<?php
echo form_open_multipart('admin/news/write');
echo form_input('headline', 'overskrift');
echo form_upload('newsImage');
echo form_textarea('description', 'indhold');
echo form_textarea('content', 'content');
echo form_submit('create', 'Opret nyhed');
echo form_close();
?>
</div><!-- inputStyle -->
I have edited your code. It may be work for you. If your folder is in root folder of application then no need to use APPPATH. I have also edited this in your code. Try this.
//Write post when logged in as admin
function write()
{
//insert image
$config['upload_path'] = 'archive/img/news/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('newsImage');
$file_data = $this->upload->data();
$newsData = array(
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'content' => $this->input->post('content'),
'creater' => $this->session->userdata('username'),
'ip' => $this->session->userdata('ip'),
'imgPath' => $_FILES['newsImage']['name']
);
echo "<pre>";
//print_r( $this->upload->data());
//print_r($file_data);
//print_r($_FILES);
//print_r($this->input->post());
print_r($newsData);
echo "</pre>";
$this->load->model('admin/news_model');
$this->news_model->insertNews($newsData);
$data['main_content'] = 'admin/write_view';
$this->load->view('template', $data);
}

Categories