I am trying to upload multiple images in Codeigniter and reduce the size of each image.
here is my view
<?php echo form_open_multipart('main_controller/do_insert');?>
<div id="mainDiv">
<div class='group'>
<div><input type="text" name="name[]"/></div>
<div><input type="file" name="img[]"/></div>
</div>
</div>
<input type="button" id="add an entry">
<input type="submit" value="save all"/>
<?php from_close();?>
and my javascript is look like
<script>
function add(x)
{
var str1="<div><input type='text' name='name"+x+"'/></div>"
var str2="<div><input type='file' name='img"+x+"'/></div>"
var str3="<input type='button' value='add an entry' onClick='add(x+1)'>";
$("#mainDiv").append(str1+str2+str3);
}
</script>
here is my controller
function do_insert{
while($i<=$counter) /*conter have value of total number for images just ignore*/
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($userfileName))
{
echo "error".count;
}
else
{
$data = array('upload_data' => $this->upload->data());
$img=$data['upload_data']['file_name']; /*for geting uploaded image name*/
$config['image_library'] = 'gd2';
$config['source_image'] = './images/'.$img;
$config['new_image'] = './images/';
$config['maintain_ratio'] = TRUE;
$config['width'] = 640;
$config['height'] = 480;
$this->load->library('image_lib', $config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
else
{
echo "success"; /*and some code here*/
}
}
}
}
my problem is that only the first image is getting re-sized remains kept as its original size.
And the image is resized after once uploaded. I think this is not a proper way now
Is there any alternative way to resize the image? it may be better if resize before doing the upload.
I have solved the problem resizing first image by making changes in my controller as `
$this->load->library('image_lib');
while($i<=$counter) /*conter have value of total number for images just ignore*/
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($userfileName))
{
echo "error".count;
}
else
{
$image_data = $this->upload->data();
$configer = array(
'image_library' => 'gd2',
'source_image' => $image_data['full_path'],
'maintain_ratio' => TRUE,
'width' => 250,
'height' => 250,
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
}
}
I solved image resize before upload image in codeigniter use this simple code.
image.php
<form id="thumb_form" enctype="multipart/form-data" method="post">
<div style="margin-bottom: 5px;">
<label>Choose Image File</label>
<input id="image" name="image" type="file" class="form-control"/>
</div>
<div>
<input type="submit" class="btn btn-primary" name="add_video" id="add_video" value="Submit">
</div>
</form>
//ajax call write here
ajax call or script
<script>
$("form#thumb_form").submit(function(event)
{
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url : "<?php echo site_url('Welcome/add_image_thumb');?>",
type : "POST",
data: formData,
contentType: false,
processData: false,
dataType:"JSON",
success : function(result)
{
alert(result);
}
});
});
Welcome.php
public function add_image_thumb()
{
if($_FILES['image']['name']=='')
{
$data['file_err']='please choose image';
}
else
{
$data = $_FILES['image']['name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $_FILES['image']['tmp_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 300;
$config['height'] = 300;
$config['new_image'] = 'asstes/thumb/' . $data;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$img = '<img src="' . base_url() . 'asstes/thumb/' . $data . '">';
echo json_encode(array('img' => $img));
}
}
//Here is my upload controller and really works in local and server
//load you image_lib to your config
$config = array(
'upload_path' => './upload/',
'log_threshold' => 1,
'allowed_types' => 'jpg|png|jpeg|gif|JPEG|JPG|PNG',
'max_size' => 10000,
'max_width'=>0,
'overwrite' => false
);
for($i = 1 ; $i <=8 ; $i++) {
$upload = 'upload'.$i; //set var in upload
if(!empty($upload)){
$this->load->library('upload', $config);
$this->upload->do_upload('upload'.$i);
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
// process resize image before upload
$configer = array(
'image_library' => 'gd2',
'source_image' => $upload_data['full_path'],
'create_thumb' => FALSE,//tell the CI do not create thumbnail on image
'maintain_ratio' => TRUE,
'quality' => '40%', //tell CI to reduce the image quality and affect the image size
'width' => 640,//new size of image
'height' => 480,//new size of image
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
}
}
Related
I have a form where some image file fields are, submitting all those value to my controller,
After Receiving all fields i'm able to resize only one field of image file rest of image fields are not going to resizing.
Here is my view
<input type="file" name="image" size="20" />
<input type="file" name="image2" size="20" />
<input type="submit" value="upload" />
here is my controller
public function resizeImage($filename){
$source_path = './upload/' . $filename;
$target_path = './upload/';
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 500,
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
}
public function uploadImage() {
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
$uploadedImage = $this->upload->data();
$this->resizeImage($uploadedImage['file_name']);
print_r('Image Uploaded Successfully.');
/*exit;*/
}
if ($this->upload->do_upload('image2')) {
$error = array('error' => $this->upload->display_errors());
$uploadedImage = $this->upload->data();
$this->resizeImage($uploadedImage['file_name']);
print_r('Image Uploaded Successfully.');
/*exit;*/
}
}
To resize image i have made a function where i'm passing the image details and image can be resize their size. But its only resizing only one time, second time image uploading with their normal size.
When you use codeigniter upload library, to change the config you must use initialize.
public function resizeImage($filename){
$source_path = './upload/' . $filename;
$target_path = './upload/';
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 500,
);
//change load library to initialize
$this->image_lib->initialize($config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
}
$this->load->library('upload', $config);
$this->load->library('image_lib');//load library outside your resizeImage function
if ($this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
$uploadedImage = $this->upload->data();
$this->resizeImage($uploadedImage['file_name']);
print_r('Image Uploaded Successfully.');
/*exit;*/
}
if ($this->upload->do_upload('image2')) {
$error = array('error' => $this->upload->display_errors());
$uploadedImage = $this->upload->data();
$this->resizeImage($uploadedImage['file_name']);
print_r('Image Uploaded Successfully.');
/*exit;*/
}
Following is my controller In this I am using two if statements one for multiple images and another is for the featured image.. my images are uploaded in a folder very well but multiple names are not inserted in the database...Only one file name is inserted in the database...
public function uploadApi()
{
if (isset($_FILES['userfile'])) {
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 200000;
$config['max_width'] = 2024;
$config['max_height'] = 1768;
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$data = array( $this->upload->data());
$this->m->update_post($data[0]['file_name']);
}
if(isset($_FILES['userfile1'])) {
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 200000;
$config['max_width'] = 2024;
$config['max_height'] = 1768;
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile1');
$data = array( $this->upload->data());
$this->m->update_feature($data[0]['file_name']);
}
}
This is a model ..
#-Update images Post-#
public function update_post($picture) {
$post = array(
'post_images'=>$picture,
);
$this->db
->where('post_status','draft')
->update('post',$post);
return true;
}
public function update_feature($picture) {
$post = array(
'post_featured_image'=>$picture,
);
$this->db
// ->set('post_created', 'NOW()', FALSE)
->where('post_status','draft')
->update('post',$post);
return true;
}
filepond plugin script
FilePond.registerPlugin(
FilePondPluginFileValidateSize,
FilePondPluginImageExifOrientation,
FilePondPluginImageCrop,
FilePondPluginImageResize,
FilePondPluginImagePreview,
FilePondPluginImageTransform
);
// Set default FilePond options
FilePond.setOptions({
// maximum allowed file size
maxFileSize: '50MB',
imagePreviewHeight: 100,
imagePreviewWidth: 200,
instantUpload: true,
// crop the image to a 1:1 ratio
imageCropAspectRatio: '1:1',
// upload to this server end point
server: {
url: '<?php echo base_url() ?>Admin/uploadApi',
}
});
var pond = FilePond.create(document.querySelector('input[name="userfile"]'));
var pond = FilePond.create(document.querySelector('input[name="userfile1"]'));
**This is a view ..**
<form method="post" enctype="multipart/form-data" class="toggle-disabled" action="<?php echo base_url() ?>Admin/update_post1" id='ritesh'>
<div class="col-md-6">
<div class="form-group">
<label>Upload images</label>
<input type="file"
class="filepond"
name="userfile"
multiple
data-max-file-size="5MB"
data-max-files="50" data-validation="required extension" />
</div>
<div class="form-group">
<label>Feature image</label>
<input type="file"
class="filepond"
name="userfile1"
data-max-file-size="5MB"
data-validation="required extension"
/>
</div>
</form>
For multiple image upload you should post images array like; imagename[]. Your current approach is not good.
You must try already posted answers:
Multiple image upload with CodeIgniter
Multiple image upload with Codeigniter saving only one file path to MySQL Database
https://www.codexworld.com/codeigniter-upload-multiple-files-images/
Please try to this in controller
function uploadApi() {
$image = $_FILES;
foreach ($image as $key => $img) {
if (!is_dir('./Uploads/')) {
mkdir('./Uploads/', 0777, TRUE);
}
if (!empty($img['name'])) {
$config['upload_path'] = './Uploads/Products/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$config['file_name'] = date('U') . '_' . $img['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
die;
} else {
if ($this->upload->do_upload($key)) {
$image_data = $this->upload->data();
$update["userfile"] = $config['file_name'];
$res = $this->m->update_post($update);
}
}
}
}
$this->load->view('imgtest');
}
I have used some code I found before to upload 1 image at a time and this works perfect. I would like to use the same style of code but for multiple images.
The Model:
function cover_upload($afbeelding) {
// path where the picture needs to be uploaded
echo $album_path = APPPATH . 'images/covers';
// configuration for the upload
$ext = end(explode(".", $_FILES['userfile']['name']));
$config = array(
'file_name' => $afbeelding . '.' . $ext,
'upload_path' => $album_path,
'allowed_types' => 'gif|jpg|jpeg|png',
'max_size' => '5120'
);
// load upload library with the configuration
$this->load->library('upload', $config);
// upload picture with the upload library
if (!$this->upload->do_upload()) {
echo $this->upload->display_errors();
die();
}
// get data array of the uploaded picture
$image_data = $this->upload->data();
// configuration for the picture thumbnail resize
echo $image_data['full_path'];
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => realpath($album_path . '/thumb'),
'maintain_ration' => TRUE,
'width' => 300,
'height' => 300
);
// load image manupulation library with the configuration
$this->load->library('image_lib', $config);
// resize picture
$this->image_lib->resize();
$this->image_lib->clear();
// submit file name of the uploaded picture to save it in the database
$bestandsnaam = $image_data['file_name'];
return $bestandsnaam;
}
the view (just the part about the image):
<div class="form-group">
<label class="col-sm-2 control-label" for="CoverFoto">picture</label>
<div class="col-sm-5">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-default btn-file"><span class="fileinput-new">select_an_image</span><span class="fileinput-exists">change</span><input type="file" name="userfile"></span>
<?php echo $this->lang->line("remove"); ?>
</div>
</div>
</div>
</div>
And the controller:
if (!empty($_FILES['userfile']['name'])) {
$gamma->CoverFoto = $this->gamma_model->cover_upload(url_title($gamma->Naam, '_', true));
}
Is there a way to use this code so i can upload multiple images?
Have a look upon this code may this help in understanding you how to handle multiple images
#####################
# Uploading multiple#
# Images #
#####################
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
what's happening in code??
well $_FILE---->it is an associative array of items uploaded to the current script via the POST method.for further look this LINK
it's an automatic variable avaliable within all scopes of script
function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = LARGEPATH; //give the path to upload the image in folder
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
$config['overwrite'] = FALSE;
return $config;
}
and in your html markup don't don't forget:
Input name must be be defined as an array i.e. name="file[]"
Input element must have multiple="multiple" or just multiple
3.$this->load->library('upload'); //to load library
4.The callback, $this->upload->do_upload() will upload the file selected in the given field name to the destination folder.
5.And the callback $this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.
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;
}
I am trying make it so when the user uploads their profile picture it resizes it to a size of 180x180 to fit in the profile picture box. I then want it to also create a thumbnail version of that image so I can use it for posts etc. This is the code I have right now:
function do_upload_profilepicture()
{
$this->load->model('model_users');
$userID = $this->model_users->getUserID($this->session->userdata('username'));
$config['upload_path'] = './img/profilepictures/';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = TRUE;
$config['file_name'] = $userID;
$config['max_size'] = '500';
$config['max_width'] = '1920';
$config['max_height'] = '1028';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_profilepic_form', $error);
}
else
{
$upload_data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = $upload_data['full_path'];
$resize['maintain_ratio'] = FALSE;
$resize['width'] = 180;
$resize['height'] = 180;
$this->load->library('image_lib', $resize);
$this->image_lib->resize();
$this->model_users->setProfilePic($userID, $upload_data['orig_name']);
redirect('upload/create_thumb/' . $upload_data['orig_name']);
}
}
function create_thumb() {
$this->load->model('model_users');
$userID = $this->model_users->getUserID($this->session->userdata('username'));
$imgname = $this->model_users->parseURL($_SERVER['REQUEST_URI'], 1);
$source_path = $imgsrc;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => 'img/profilepictures/' . $imgname,
'new_image' => base_url() . 'img/profilepictures/thumbs/' . $imgname,
'maintain_ratio' => TRUE,
'width' => 50,
'height' => 50
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear //
$this->image_lib->clear();
redirect('userprofile/home/' . $userID);
}
}
What happens is it isnt creating the new file, why is this? Is there an easier way to do this?
one problem which i found in your code you are redirecting user just for creating thumbnail you can do in on step just calling that method in do_upload_profilepicture method and pass image name no need to redirect again and again.
function do_upload_profilepicture()
{
$this->load->model('model_users');
$userID = $this->model_users->getUserID($this->session->userdata('username'));
$config['upload_path'] = './img/profilepictures/';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = TRUE;
$config['file_name'] = $userID;
$config['max_size'] = '500';
$config['max_width'] = '1920';
$config['max_height'] = '1028';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_profilepic_form', $error);
}
else
{
$upload_data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = $upload_data['full_path'];
$resize['maintain_ratio'] = FALSE;
$resize['width'] = 180;
$resize['height'] = 180;
$this->load->library('image_lib', $resize);
$this->image_lib->resize();
$this->image_lib->clear();
$this->model_users->setProfilePic($userID, $upload_data['orig_name']);
$this->create_thumb( $upload_data['orig_name']);
redirect('userprofile/home/' . $userID);
}
}
function create_thumb($imgname) {
$source_path = $imgsrc;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => 'img/profilepictures/' . $imgname,
'new_image' => 'img/profilepictures/thumbs/' . $imgname,
'maintain_ratio' => TRUE,
'width' => 50,
'height' => 50
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear //
$this->image_lib->clear();
}
}
you also using base_url in new_image for thumb you need to give file path not http path. i will suggest you to use this library for creating image on fly in codeigniter codeigniter-advanced-images