Codeigniter: resizing multiple uploaded images gets only one image resized - codeigniter

I'm trying to resize all uploaded images uploaded from a form and save a resized copy in another folder. This method works fine with a single image upload not in a multiple image upload. The issue here that I get only 1 image resized. Here's the upload and resize code:
$this->load->library('upload');
$dataInfo = array();
$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];
$config = array();
$config['upload_path'] = realpath(APPPATH . '../images/myfolder/');
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['overwrite'] = FALSE;
$rand_string = $this->generateRandomString(3);
$ext = strtolower(pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION));
$filename = round(microtime(true) * 1000).$rand_string.'.'.$ext;
$config['file_name'] = $filename;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
$this->resizeImage($filename);
$dataInfo[] = $this->upload->data();
}
}
Resizing function
public function resizeImage($filename)
{
$source_path = realpath(APPPATH . '../images/myfolder/'.$filename) ;
$target_path = realpath(APPPATH . '../images/myfolder/thumbs/') ;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'create_thumb' => TRUE,
'thumb_marker' => '',
'width' => 200,
'height' => 200
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
$this->image_lib->clear();
}
But I get just 1 image resize though all images are uploaded not just one. Why is this happening and how to fix i?

Assuming that all your images are getting uploaded (that is the case right?) then I would suggest trying: $this->upload->initialize($config, true); and:
$this->load->library('image_lib');
$this->image_lib->initialize($config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}

Related

Convert uploaded pdf file to jpg in codeigniter

I am currently beginning to learn CodeIgniter. There is this site that I've been working on.
In this site, users can upload PDF files but they are only allowed to view their uploaded files in JPG format. The question is, how can I convert the PDF file into JPG on the time of upload and store JPG format instead of PDF.
here is the code of my CONTROLLER
public function upload()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['permission'] = $session_data['permission'];
if($data['permission']=='Super Admin' || $data['permission']=='Admin'){
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
}
else
{
redirect('login', 'refresh');
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '10000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('header');
$this->load->view('upload_form', array('error' => ' ' ));
}
else
{
$data = array('upload_data' => $this->upload->data());
$upload_data = $this->upload->data();
$session_data = $this->session->userdata('logged_in');
$first = $session_data['firstname'];
$last = $session_data['lastname'];
$dept = $session_data['department'];
$uploader = $first." ".$last;
$name = $upload_data['file_name'];
$path = $upload_data['file_path'];
$this->db->query("INSERT INTO tbl_uploaded
(`uploaded_id`, `name`, `path`,`department`,`uploader`)
VALUES ('','".$name."',
'". $path."','".$dept."','".$uploader."')");
redirect('csfi','refresh');
}
}
I've already read about Imagick but I don't know how to use it in CodeIgniter. Can you give me some tutorials and examples or a much easier way to convert PDF to JPG in CodeIgniter?
Thank you in advance guys.
$config = array();
$config['allowed_types'] = 'pdf';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
// Image manipulation library
$this->load->library('image_lib');
foreach ($notes['name'] as $key => $note)
{
$_FILES['notes']['name'] = $notes['name'][$key];
$_FILES['notes']['type'] = $notes['type'][$key];
$_FILES['notes']['tmp_name'] = $notes['tmp_name'][$key];
$_FILES['notes']['error'] = $notes['error'][$key];
$_FILES['notes']['size'] = $notes['size'][$key];
$extension = pathinfo($_FILES['notes']['name'], PATHINFO_EXTENSION);
$unique_no = uniqid(rand(), true);
$filename[$key] = $unique_no.'.'.$extension; // with ex
$filename2[$key] = $unique_no; // without ex
$target_path = "notes_files/";
if (!is_dir($target_path))
{
mkdir('./'.$target_path, 0777, true);
}
$config['file_name'] = $filename[$key];
$config['upload_path'] = './'.$target_path;
$this->upload->initialize($config);
if (! $this->upload->do_upload('notes'))
{
return array('error' => $this->upload->display_errors());
}
// converting pdf to images with imagick
$im = new Imagick();
$im->setResolution(160,220);
$ig = 0;
while(true)
{
try {
$im->readimage($config['upload_path'].$config['file_name']."[$ig]");
} catch (Exception $e) {
$ig = -1;
}
if($ig === -1) break;
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);
$im->setImageFormat('jpg');
$image_name = $filename2[$key]."_$ig".'.jpg';
$imageprops = $im->getImageGeometry();
$im->writeImage($config['upload_path'] .$image_name);
$im->clear();
$im->destroy();
// change file permission for file manipulation
chmod($config['upload_path'].$image_name, 0777); // CHMOD file
// add watermark to image
$img_manip = array();
$img_manip = array(
'image_library' => 'gd2',
'wm_type' => 'overlay',
'wm_overlay_path' => FCPATH . '/uploads/institutes/'.$institute_logo, // path to watermark image
'wm_x_transp' => '10',
'wm_y_transp' => '10',
'wm_opacity' => '10',
'wm_vrt_alignment' => 'middle',
'wm_hor_alignment' => 'center',
'source_image' => $config['upload_path'].$image_name
);
$this->image_lib->initialize($img_manip);
$this->image_lib->watermark();
ImageJPEG(ImageCreateFromString(file_get_contents($config['upload_path'].$image_name)), $config['upload_path'].$image_name, );
$ig++;
}
// unlink the original pdf file
chmod($config['upload_path'].$config['file_name'], 0777); // CHMOD file
unlink($config['upload_path'].$config['file_name']); // remove file
}
// echo '<p>Success</p>';exit;
die(json_encode(array(
'data' => 'Success',
'status' => 'success'
)));
Try this, you can upload and convert multiple files using this.

When 2 different images are uploaded to 2 different folders,then the images are uploaded.but the thumbs are not created

Here is my controller function, please help me to create the thumbs of both images. Only the images are uploaded to the folder. i created a function named resize to create the thumbs. that's also given in the controller.
public function add() {
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$this->load->library('form_validation');
$this->form_validation->set_rules('txtPrdname', 'Product Name', 'trim|required|htmlspecialchars');
$this->form_validation->set_rules('sbPrdcategory', 'Product Category', 'trim|required|htmlspecialchars');
$this->form_validation->set_rules('sbPrduser', 'Managing User', 'trim|required|htmlspecialchars');
$this->form_validation->set_rules('txtPrdprofile', 'Product Profile', 'trim|required|htmlspecialchars');
if ($this->form_validation->run() == FALSE) {
$data_view["error"] = "";
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
$this->load->view('moderator/b2bproduct_add', $data_view);
$this->load->view('moderator/templates/footer');
} else {
// Image uploading codes
$config['upload_path'] = 'assets/images/b2bproduct';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
if (isset($_FILES['filePrdimage']['name'])) {
$config['file_name'] = substr(md5(time()), 0, 28) . $_FILES['filePrdimage']['name'];
}
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload('filePrdimage')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat = array('upload_data' => $this->upload->data());
$this->load->library('upload');
$this->upload->initialize($config);
$this->resize($dat['upload_data']['full_path'], 'assets/images/b2bproduct/thump/' . $dat['upload_data']['file_name'], 180, 400);
}
if (empty($dat['upload_data']['file_name'])) {
$prdimage = '';
} else {
$prdimage = $dat['upload_data']['file_name'];
}
// End Image uploading Codes
// Logo uploading codes
$config['upload_path'] = 'assets/images/b2blogo';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
if (isset($_FILES['filePrdlogo']['name'])) {
$config['file_name'] = substr(md5(time()), 0, 28) . $_FILES['filePrdlogo']['name'];
}
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload('filePrdlogo')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat1 = array('upload_data' => $this->upload->data());
$this->load->library("upload",$config);
$this->resize($dat1['upload_data']['full_path'], 'assets/images/b2blogo/thump/' . $dat1['upload_data']['file_name'], 180, 400);
}
if (empty($dat1['upload_data']['file_name'])) {
$prdlogo = '';
} else {
$prdlogo = $dat1['upload_data']['file_name'];
}
// End Logo uploading Codes
$data = array(
'prd_name' => $this->input->post('txtPrdname'),
'prd_category' => $this->input->post('sbPrdcategory'),
'prd_user' => $this->input->post('sbPrduser'),
'prd_profile' => $this->input->post('txtPrdprofile'),
'prd_oem' => $this->input->post('rbtnPrdoem'),
'prd_protype' => $this->input->post('rbtnPrdprotype'),
'prd_image' => $prdimage,
'prd_ranktype' => $this->input->post('sbPrdranktype'),
'prd_points' => $this->input->post('txtPrdpoints'),
'prd_extrakey' => $this->input->post('txtPrdextrakey'),
'prd_dated' => time(),
'prd_ipadd' => $_SERVER['REMOTE_ADDR']
);
$result_id = $this->b2bproduct_model->add($data);
if ($result_id) {
redirect(base_url() . 'moderator/b2bproduct/view/' . $result_id, 'refresh');
} else {
$data_view["error"] = "Data can't insert due to database error";
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
$this->load->view('moderator/b2bproduct_add', $data_view);
$this->load->view('moderator/templates/footer');
}
}
}
Resize function
public function resize($source, $destination, $width, $height) {
$config['image_library'] = 'gd2';
$config['source_image'] = $source;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = $destination;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
First of all you are loading library two times in your function add please load it one time probably at the top of function.
in resize use $this->image_lib->initialize($config) as below
public function resize($source, $destination, $width, $height) {
$config['image_library'] = 'gd2';
$config['source_image'] = $source;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = $destination;
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
Is it possible that the folders for your thumbs (assets/images/b2bproduct/thump/ and assets/images/b2blogo/thump/) do not exist?
It is very likely the reason to be a simple spelling mistake like thump instead of thumb.
EDIT:
You really don't have to load the upload and image_lib libraries so many times. Do it once at the beginning. After that you can use $this->upload->initialize($config); or $this->image_lib->initialize($config); to all these places where now you are trying to re-load the libraries.
To make your code works you should at least add $this->image_lib->initialize($config); before $this->image_lib->resize(); in your resize function.

How to delete a image file?

How can i delete image files from uploaded folder in codeigniter from delete button??
Can any one guide me ???
Here is my controller that upload image files
private function upload() {
$config['upload_path'] = 'assets/uploads/orginal/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|x-png';
$config['max_size'] = '500';
$config['max_width'] = '1600';
$config['max_height'] = '1200';
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$img = $this->upload->data();
// create thumbnail
$new_image = 'assets/uploads/thumbs/' . $img['file_name'];
$c_img_lib = array(
'image_library' => 'gd2',
'source_image' => $img['full_path'],
'maintain_ratio' => TRUE,
'width' => 100,
'height' => 100,
'new_image' => $new_image
);
$this->load->library('image_lib', $c_img_lib);
$this->image_lib->resize();
} else {
$this->data['error'] = $this->upload->display_errors();
}
}
Use the unlink() function:
unlink($new_image);
http://pt1.php.net/manual/en/function.unlink.php

Upload Multiple Images and Generate Large Size

I have already generated a code that will upload multiple images in codeigniter, however I can't generate a large size of the uploaded images to other directory using codeigniter image library.
Using the codes below, it will only generate one image even though if the user uploaded multiple images.
function insert_prod(){
$foldername = $_POST['folder'];
$path = './uploads/products/'.$foldername;
mkdir($path, 0777, true);
mkdir($path.'/zoomimages', 0777, true);
$config = array();
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$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];
$config['file_name'] = 'img_'.$i;
$this->upload->initialize($config);
$this->upload->do_upload();
$upload_data = array('upload_data' => $this->upload->data());
$full_path = $upload_data['upload_data']['full_path'];
$u_data = $upload_data['upload_data'];
// var_dump( $this->upload->data());
// var_dump($upload_data);
echo $cpt;
$config1['image_library'] = 'gd2';
$config1['source_image'] = $full_path;
$config1['new_image'] =$path.'/zoomimages';
$config1['create_thumb'] = FALSE;
$config1['maintain_ratio'] = TRUE;
$config1['width'] = 300;
$config1['height'] = 300;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
You are loading library with $this->load->library('image_lib', $config1); inside your loop so codeigniter see the class is already load so its not setting your $config1 again
Move $this->load->library('image_lib'); out side your loop
Then add $this->image_lib->initialize($config1); instant of $this->load->library('image_lib', $config1);

CI multiple image resizing

I'm uplaoding multiple images with CI, they do upload. I am also trying to resize them,
with the following code, only the first image resizes, rest of them don't. They get uploaded with their current size.
What's wrong?
Any help'd be really, really appreciated.
function doupload() {
$path = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value){
for($n=0; $n<=$count-1; $n++) {
$_FILES['userfile']['name']=$value['name'][$n];
$_FILES['userfile']['type'] = $value['type'][$n];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$n];
$_FILES['userfile']['error'] = $value['error'][$n];
$_FILES['userfile']['size'] = $value['size'][$n];
$config['upload_path'] = './images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$path[] = $data['full_path']; //contains full path of every image
}
}
foreach($path as $p=>$ath){
$config1 = array(
'source_image' => $ath,
'new_image' => './images',
'maintain_ration' => true,
'overwrite' => true,
'width' => 600,
'height' => 400
);
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
first load image_lib outside loop you can use initialize in loop and pass new config for every image
$this->load->library('image_lib');
foreach($path as $p=>$ath){
$config1 = array(
'source_image' => $ath,
'new_image' => './images',
'maintain_ration' => true,
'overwrite' => true,
'width' => 600,
'height' => 400
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}
CodeIgniter's Loader class loads libraries only once, so in your foreach you resize the same image multiple times. Move the library loading out of the loop and use the initialize method of Image Manipulation library to set the config for every resize.
in my case load lib in constructor and use code
$config['image_library'] = 'gd2';
$config['maintain_ratio'] = FALSE;
$config['source_image'] = $config['upload_path'].$image_info['file_name'];
$config['new_image'] = $config['upload_path']."thumb_".$image_info['file_name'];
$config['width'] = 313;
$config['height'] = 303;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
$config['new_image'] = $config['upload_path']."icon_".$image_info['file_name'];
$config['width'] = 70;
$config['height'] = 70;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
keep index name always new_image in $config['new_image']

Resources