How to resize image on codeigniter? - codeigniter

I get a module like a blog, and I must upload an image to my website. but when I upload my image not be resized/cropped automatically.
CONTROLLER
function simpan_campaign(){
$config['upload_path'] = './assets/images/upload'; //path folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
$config['encrypt_name'] = TRUE; //Enkripsi nama yang terupload
$this->upload->initialize($config);
if(!empty($_FILES['filefoto']['name'])){
if ($this->upload->do_upload('filefoto')){
$gbr = $this->upload->data();
//Compress Image
$config['image_library']='gd2';
$config['source_image']='./assets/images/upload'.$gbr['file_name'];
$config['create_thumb']= FALSE;
$config['maintain_ratio']= FALSE;
$config['quality']= '50%';
$config['width']= 380;
$config['height']= 264;
$config['new_image']= './assets/images/upload'.$gbr['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
$image=$gbr['file_name'];
$title=$this->input->post('title');
$cashtarget=$this->input->post('cashtarget');
$campcode=$this->input->post('campcode');
$datefrom=$this->input->post('datefrom');
$dateend=$this->input->post('dateend');
$category=$this->input->post('category');
$desc=$this->input->post('description');
$this->main_model->save_campaign($title,$desc,$image,$cashtarget,$campcode,$datefrom,$dateend,$category);
echo "Image berhasil diupload";
redirect('account/add');
}
}else{
echo "Image yang diupload kosong";
}
}
and my model like :
MODEL
function save_campaign
($title,$desc,$image,$cashtarget,$campcode,$datefrom,$dateend,$category){
$hsl=$this->db->query("INSERT INTO tcampaign (title,description,pathimage,cashtarget,campcode,datefrom,dateend,category) VALUES ('$title','$desc','$image','$cashtarget','$campcode','$datefrom','$dateend','$category')");
return $hsl;
}
I can upload but i cant resize or crop on my view

I suspect that the biggest problem was this declaration:
'./assets/images/upload'.$gbr['file_name']; if you notice there is no ending slash before the filename...
Also you used the same variable $config for both upload and resizing. This can also cause some unexpected results. Just use a different variable for both. Here we have $upconfig and $config.
I've also cleaned up the function a bit and added in the error methods so you can see what is going wrong if something does. You should handle the errors more elegantly than just echoing them.
function simpan_campaign() {
$this->load->library('upload'); // not sure if you already autoloaded this
// this way $config won't overwrite or add on to the upload config
$upconfig['upload_path'] = './assets/images/upload/'; // missing end slash
$upconfig['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$upconfig['encrypt_name'] = TRUE;
$this->upload->initialize($upconfig);
if (!empty($_FILES['filefoto']['name'])) {
if ($this->upload->do_upload('filefoto')) {
$filename = $this->upload->data('file_name');
//Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = $this->upload->data('full_path'); // missing slash before name
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '50%';
$config['width'] = 380;
$config['height'] = 264;
// not required as you have declared the same filename
// the original image will be targeted for resize
//$config['new_image'] = './assets/images/upload/' . $filename;
$this->load->library('image_lib');
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
$title = $this->input->post('title');
$cashtarget = $this->input->post('cashtarget');
$campcode = $this->input->post('campcode');
$datefrom = $this->input->post('datefrom');
$dateend = $this->input->post('dateend');
$category = $this->input->post('category');
$desc = $this->input->post('description');
$this->main_model->save_campaign($title, $desc, $filename, $cashtarget, $campcode, $datefrom, $dateend, $category);
echo "Image berhasil diupload";
redirect('account/add');
} else {
echo $this->upload->display_errors();
exit;
}
} else {
echo "Image yang diupload kosong";
}
}

Related

codeiginter upload and resize

I have a problem with CI class image, image does not resize...
for example :
controller
private function _do_upload(){
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000; //set max size allowed in Kilobyte
$config['max_width'] = 1000; // set max width image allowed
$config['max_height'] = 1000; // set max height allowed
$config['file_name'] = round(microtime(true) * 1000);
$this->load->library('upload', $config);
if($this->upload->do_upload('photo')) //upload and validate{
$config2['image_library'] = 'gd2';
$config2['source_image'] = $this->upload->upload_path;
$config2['create_thumb'] = TRUE;
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 450;
$config2['height'] = 500;
$this->load->library('image_lib', $config2);
if(!$this->image_lib->resize()){
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('','');
$data['status'] = FALSE;
}
return $this->upload->data('file_name');
}else{
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('',''); //show ajax error
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
}
But i got no error, I dont know where is the mistake?
Well you have a few issues...
1. You have commented out your opening { which would break your code.
if($this->upload->do_upload('photo')) //upload and validate {
Should be
if($this->upload->do_upload('photo')) { //upload and validate
2. The next part: If you do have a resize error you are not doing anything with your messages... So...
if(!$this->image_lib->resize()){
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('','');
$data['status'] = FALSE;
}
Needs the added json_encode like..
if(!$this->image_lib->resize()){
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('','');
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
In reference to your resizing, you do need to supply the images full filename and not just the path where "files" live...
Your source_image is a Path to where the files are uploaded to. Not the Path/Filename of the image you want to resize...
$config2['source_image'] = $this->upload->upload_path;
So if you add this line that gives you the full path and filename and use it...
$file_data = $this->upload->data();
$config2['source_image'] = $file_data['full_path'];
Does that work better?

Codeigniter image resize() thumbnail name should have same name

Here my controller file this working fine except in thumbs folder name get changed to converted_thumb
example:
my original image name is converted.jpg but in thumbs folder it save as converted_thumb so i want to remove _thumb from image name please solve this issue
public function do_upload() {
$config['upload_path'] = './uploads'; // uploaded file store here
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = ' 2097152';
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$data = $this->upload->data();
//create copy of image
$configs['image_library'] = 'gd2';
$configs['source_image'] = $data['full_path'];
$configs['new_image'] = 'uploads/thumbs/'; //resize image will save here
$configs['create_thumb'] = 'false';
$configs['width'] = '250';
$configs['height'] = '250';
$this->load->library('image_lib', $configs);
$this->image_lib->resize();
$image_name = $data['file_name'];
//$full_path = $data['full_path'];
$post = array(
'product_name' => $image_name,
'product_path' => $configs['new_image'].$image_name
);
$this->db->insert('project', $post);
} else {
echo $this->upload->display_errors();
}
}
}
Why wouldn't you like the _thumbs from that? It is what it is for. Anyway do this.
rename("<?php echo base_url()?>/uploads/thumbs/YOUR_FILE_NAME_THUMBS", "<?php echo base_url()?>/uploads/thumbs/YOUR_FILE_NAME");
Try thumb_marker in your $configs array.
$configs['image_library'] = 'gd2';
$configs['source_image'] = $data['full_path'];
$configs['new_image'] = 'uploads/thumbs/'; //resize image will save here
$configs['create_thumb'] = 'false';
$configs['thumb_marker'] = ''; //Add this in your config array empty string
Then '_thumb' will not add in your newly created files. Source for more detail.
Just add thumb_marker to your config array and set it to FALSE
$configs['image_library'] = 'gd2';
$configs['source_image'] = $data['full_path'];
$configs['new_image'] = 'uploads/thumbs/'; //resize image will save here
$configs['create_thumb'] = 'false';
$configs['thumb_marker'] = FALSE; //this will remove the "_thumb" to your thumb image name
$configs['width'] = '250';
$configs['height'] = '250';

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.

SImple solution to Codeigniter image class?

I have some messy code, even i use SimpleImage, i know i can use CodeIgniter image class, but config is little big, can someone post a little elegant and better solution, this is my code for now, i want to get rid of SimpleImage, and image class is initialized in controller.Here is what i have:
// Main config
$config['image_library'] = 'gd2';
$config['maintain_ratio'] = TRUE;
$config['height'] = '1';
$config['master_dim'] = 'width';
$config['overwrite'] = TRUE;
// Resize image with SimpleImage
$novaslika="img/proizvodi/".$last.".jpg";
$image = new SimpleImage();
$image->load($_FILES['slika']['tmp_name']);
$image->resizeToWidth(800);
$image->save($novaslika);
// Create PNG
$config['source_image'] = $_FILES['maska']['tmp_name'];
$config['width'] = 800;
$config['new_image'] = "./img/proizvodi/".$last."_maska.png";
$this->image_lib->initialize($config);
$this->image_lib->resize();
// Create thumb
$config['source_image'] = './img/proizvodi/'.$last.'.jpg';
$config['create_thumb'] = TRUE;
$config['new_image'] = './img/proizvodi/thumbs/'.$last.'_thumb.jpg';
$this->image_lib->initialize($config);
$this->image_lib->resize();
You can do something like this:
function index()
{
$this->load->library('image_lib');
$a = array(
'source_image' => 'images/1.jpg',
'width' => 100,
'height' => 100,
'new_image' => 'images/2.jpg',
'create_thumb' => TRUE,
'overwrite' => FALSE
);
$image = $this->_image_manipulation($a);
if($image === TRUE)
{
echo "IMAGE OK";
}
else
{
echo $image;
}
}
private function _image_manipulation($configs = '')
{
if($configs)
{
$config['image_library'] = 'gd2'; //static
$config['maintain_ratio'] = TRUE; //static
$config['master_dim'] = 'width'; //static
$config['source_image'] = $configs['source_image'];//required
$config['height'] = (isset($configs['height']))?$configs['height']:NULL;
$config['width'] = (isset($configs['width']))?$configs['width']:NULL;
$config['overwrite'] = (isset($configs['overwrite']))?$configs['overwrite']:NULL;
$config['new_image'] = (isset($configs['new_image']))?$configs['new_image']:NULL;
$config['create_thumb'] = (isset($configs['create_thumb']))?$configs['create_thumb']:NULL;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->resize())
{
return $this->image_lib->display_errors();
}
else
{
return TRUE;
}
}
}
But will still need the SimpleImage library to convert to png's UNLESS, and I can't confirm, SimpleImage is using ImageMagick. If it is, that means it's installed on the system and you can change
$config['image_library'] = 'gd2';
to
$config['image_library'] = 'ImageMagick';
and CodeIgniter will handle the image conversion for you too; all you need to do is rename the file:
$a = array(
'source_image' => 'images/1.jpg',
'new_image' => 'images/1.png',
);

Uploading an image in codeigniter

I am trying to upload an image,create thumbnail but i get an error.
Here is my controller.
<?php
class Upload extends Controller {
function Upload()
{
parent::Controller();
$this->load->helper(array('form','url','file'));
}
function index()
{
$this->load->view('upload_form'); //Upload Form
}
function picupload()
{
//Load Model
$this->load->model('Process_image');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048'; //2 meg
$this->load->library('upload');
foreach($_FILES as $key => $value)
{
if( ! empty($key['name']))
{
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($key))
{
$errors[] = $this->upload->display_errors();
}
else
{
$this->Process_image->process_pic();
}
}
}
$data['success'] = 'Thank You, Files Upladed!';
$this->load->view('upload_success', $data); //Picture Upload View
}
}
?>
My model:
<?php
class Process_image extends Model {
function Process_image()
{
parent::Model();
$this->load->library('image_lib');
//Generate random Activation code
function generate_code($length = 10){
if ($length <= 0)
{
return false;
}
$code = "";
$chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
srand((double)microtime() * 1000000);
for ($i = 0; $i < $length; $i++)
{
$code = $code . substr($chars, rand() % strlen($chars), 1);
}
return $code;
}
}
function process_pic()
{
//Connect to database
$this->load->database();
//Get File Data Info
$uploads = array($this->upload->data());
$this->load->library('image_lib');
//Move Files To User Folder
foreach($uploads as $key[] => $value)
{
//Gen Random code for new file name
$randomcode = generate_code(12);
$newimagename = $randomcode.$value['file_ext'];
//Creat Thumbnail
$config['image_library'] = 'GD2';
$config['source_image'] = $value['full_path'];
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '_tn';
$config['master_dim'] = 'width';
$config['quality'] = 75;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$config['new_image'] = '/pictures/'.$newimagename;
//$this->image_lib->clear();
$this->image_lib->initialize($config);
//$this->load->library('image_lib', $config);
$this->image_lib->resize();
//Move Uploaded Files with NEW Random name
rename($value['full_path'],'/pictures/'.$newimagename);
//Make Some Variables for Database
$imagename = $newimagename;
$thumbnail = $randomcode.'_tn'.$value['file_ext'];
$filesize = $value['file_size'];
$width = $value['image_width'];
$height = $value['image_height'];
$timestamp = time();
//Add Pic Info To Database
$this->db->set('imagename', $imagename);
$this->db->set('thumbnail', $thumbnail);
$this->db->set('filesize', $filesize);
$this->db->set('width', $width);
$this->db->set('height', $height);
$this->db->set('timestamp', $timestamp);
//Insert Info Into Database
$this->db->insert('pictures');
}
}
}
?>
The error:
A PHP Error was encountered
Severity: Warning
Message: rename(C:/wamp/www/uploads/Heaven_Clouds.jpg,/pictures/kFttl7lpE7Rk.jpg) [function.rename]: No such file or directory
Filename: models/Process_image.php
Line Number: 68
This is line 68:
rename($value['full_path'],'/pictures/'.$newimagename);
Remove the "/" before "picutres" in
rename($value['full_path'],'/pictures/'.$newimagename);
It wanna say that you want put your renamed file in a directory named "pictures" placed at the root of an Unix file system, then you're obviously in a Windows system and you do not seem to have a "pictures" directory at the root of your disk.
result :
rename($value['full_path'],'pictures/'.$newimagename);
This is a very simple script taken partly from the CI Docs:
$config['upload_path'] = 'uploads/cgm/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$configThumb = array();
$configThumb['image_library'] = 'gd2';
$configThumb['source_image'] = '';
$configThumb['create_thumb'] = TRUE;
$configThumb['maintain_ratio'] = TRUE;
$configThumb['width'] = 100;
$configThumb['height'] = 120;
$this->load->library('image_lib');
for($i = 1; $i < 6; $i++) {
$upload = $this->upload->do_upload('file'.$i);
if($upload === FALSE) continue;
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
$imgName = $this->pictures_m->addPicture(array('listing_id' => $listing_id, 'ext' => $data['file_ext'], 'picture_name' => $this->input->post('file'.$i.'name')));
if($data['is_image'] == 1) {
$configThumb['source_image'] = $data['full_path'];
$configThumb['new_image'] = $data['file_path'].$imgName.$data['file_ext'];
$this->image_lib->initialize($configThumb);
$this->image_lib->resize();
}
rename($data['full_path'], $data['file_path'].$imgName.$data['file_ext']);
}
this will take 5 images, but if you only have one, you can just change the for loop.
i had the same problem but, in my scenario i've to only upload the array of files so i did some small changes to the library 'Upload.php'
view
<form encrypt="multipart/form-data" ...>
<input type="file" name="your_name[]" />
<input type="file" name="your_name[]" />
<input type="submit" />
</form>
controller
for($i = 0; $i < count($_FILES['your_name']['name']); $i++) {
$config['upload_path'] = 'your upload path';
$this->upload->initialize($config);
$this->upload->do_upload('listing_images', $i);
endfor;
if you have single file to upload then duplicate the function in system/libraries/Upload.php
function do_upload($field) to function do_upload_array($field, $i)
put [$i] index on lines 160, 162, 196, 197
and
function _file_mime_type($_FILES[$field]) to function _file_mime_type_array($_FILES[$field], $i)
and put [$i] index on lines 1026, 1043, 1057 and 1065
thats it...
your file array will upload easily now....

Resources