I am trying to make a simple app with Codeigniter where i need to store thumbnail image path in MySql database. The images along with the thumbnail versions upload correctly in the upload folder and I can store the image path in my database while uploading but i can not store the thumbnail image path in the database. I tried this in the controller:
$thumbnail= $this->resize($data['upload_data']['full_path'], $data['upload_data'] ['file_name']);
$thumbnail_path = './uploads/'. $thumbnail;
$newRow = array(
"title" => $this->input->post('title'),
"img_path" => $imgpath,
"thumbnail_path" => $thumbnail_path,
"post_body" => $this->input->post('post_body')
)
But it only stores "./uploads/" in the thumbnail_path column in my table, not the actual thumbnail path. Where i expect it to store something like "./uploads/Lighthouse_thumb.jpg". I can not figure out how to get the path of the thumbnail images to store them in the database. Here is my full upload controller:
class Upload extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
}
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'] = '1000';
$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 {
$image_data = $this->upload->data();
$imgpath = './uploads/' . $image_data['file_name'];
$data = array('upload_data'=>$this->upload->data());
$thumbnail= $this->resize($data['upload_data']['full_path'], $data['upload_data']['file_name']);
$thumbnail_path = './uploads/'. $thumbnail;
$newRow = array(
"title" => $this->input->post('title'),
"img_path" => $imgpath,
"thumbnail_path" => $thumbnail_path,
"post_body" => $this->input->post('post_body')
);
$this->load->model('postimage_path');
$this->postimage_path->insert($newRow);
$this->load->view('upload_success', $data);
}
}
function resize($path, $file) {
$config['image_library'] = 'gd2';
$config['source_image'] = $path;
$config['create_thumb'] = TRUE;
$config['maintian_ratio'] = TRUE;
$config['width'] = 100;
$config['height'] = 100;
$config['new_image'] = './uploads/' . $file;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}
$thumbnail_path = './uploads/'. $thumbnail;
So thumbnail_path contains only "./uploads/" : that tells us that $thumbnail is false (or null or empty string etc.), meaning that the return value of the call to resize is wrong - it seems you expect it to return the file name.
function resize($path, $file) {
$config['image_library'] = 'gd2';
$config['source_image'] = $path;
$config['create_thumb'] = TRUE;
$config['maintian_ratio'] = TRUE;
$config['width'] = 100;
$config['height'] = 100;
$config['new_image'] = './uploads/' . $file;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
resize returns nothing! And you assign that nothing to $thumbnail_path. That's your problem.
You seem to have simply copied the code from the CodeIgniter docs. From said docs (emphasis mine):
The above code tells the image_resize function to look for an image called mypic.jpg located in the source_image folder, then create a thumbnail that is 75 X 50 pixels using the GD2 image_library. Since the maintain_ratio option is enabled, the thumb will be as close to the target width and height as possible while preserving the original aspect ratio. The thumbnail will be called mypic_thumb.jpg
So there you have it! If your filename is $data['upload_data']['file_name'], your thumbnail will be $data['upload_data']['file_name'] . "_thumb". Have a look at your file system, the files should be there for you to see.
So to fix your problem, this should do the trick:
$pathinfo = pathinfo($data['upload_data']['file_name']);
$thumbnail_path = './uploads/'. $data['upload_data']['file_name'] . "_thumb" . $pathinfo['extension'];
Related
I am trying to do flip operation in CodeIgniter
I have found a code for image flip in php using codeigniter libraries
First I uploaded image to a path, here is the coding of controller for this purpose:
$config['upload_path'] = 'D:/xampp/htdocs/ImageTools/assets/images/pages/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->image_lib->clear();
$this->load->library('upload',$config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image='noimage.jpg';
}else{
$file_data = $this->upload->data();
$data['img'] = base_url().'assets/images/pages/'.$file_data['file_name'];
$this->load->view('pages/inverted',$data);
I tried to do the invert operation here but couldn't succeeded then tried to invert the uploaded image, done the coding in view file by passing this uploaded image to view:
<?php $img;?>
<?php
$this->image_lib->clear();
$config=array();
$config['image_library'] = 'gd2';
$config['source_image'] = $img;
$config['create_thumb'] = TRUE;
$config['rotation_angle'] = 'hor';
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->load->library('upload',$config);
$this->image_lib->rotate();
if ( ! $this->image_lib->rotate())
{
echo $this->image_lib->display_errors();
}
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image='noimage.jpg';
}
else{
$file_data = $this->upload->data();
$data = base_url().'/assets/images/pages/'.$file_data['file_name'];
}
?>
First off D:/xampp/htdocs/ImageTools/assets/images/pages/ will never be valid in a server environment. There is a way to make it valid for all environments like so:
$config['upload_path'] = './ImageTools/assets/images/pages/';
(there are other ways but this is the one in the CI docs)
If the folder ImageTools is actually imagetools then that needs to be used in the above example; Linux is case sensitive.
Therefore, following the docs, you can do:
$upload['upload_path'] = './ImageTools/assets/images/pages/';
$upload['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $upload);
if (!$this->upload->do_upload('userfile')) {
show_error($this->upload->display_errors());
}
$this->load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image'] = $this->upload->data('full_path');
$config['rotation_angle'] = 'hor'; // or whatever
$this->image_lib->initialize($config);
if (!$this->image_lib->rotate()) {
show_error($this->image_lib->display_errors());
}
$img_path = base_url() . '/assets/images/pages/' . $this->upload->data('file_name');
echo "<img src='{$img_path}' width='auto' height='200'>";
I tried to upload two images using a form. To do that I wrote a image function.
protected function imageUploadResize($filename, $field_name, $width, $height, $maker){
// thumb image upload settings
$config['upload_path'] = './uploads/packages/';
$config['allowed_types'] = 'gif|jpg|png';
// thumb upload settings
$image_new_name = time().'_'.$filename;
$config['file_name'] = $image_new_name;
$this->load->library('upload', $config);
// upload thumb image
if ( $this->upload->do_upload($field_name)) {
// resize uploaded file
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/packages/'.$image_new_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['thumb_marker'] = $maker;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$error = array('error' => $this->upload->display_errors());
} else {
$imageData = array('upload_data' => $this->upload->data());
}
return $image_new_name;
}
And I access that function this way,
// allocate image name to data set
if(!empty($_FILES["thumb_image"]['name'])){
// thumb upload
$thumb_image_new_name = $this->imageUploadResize($_FILES["thumb_image"]['name'],'thumb_image',THUMB_IMAGE_WIDTH, THUMB_IMAGE_HEIGHT, '_thumb');
$data['thumb_image'] = $thumb_image_new_name;
}else{
$data['thumb_image'] = "";
}
// allocate image name to data set
if(!empty($_FILES["banner_image"]['name'])){
// banner upload
$banner_image_new_name = $this->imageUploadResize($_FILES["banner_image"]['name'],'banner_image',BANNER_IMAGE_WIDTH, BANNER_IMAGE_HEIGHT, '_banner');
$data['banner_image'] = $banner_image_new_name;
}else{
$data['banner_image'] = "";
}
When I upload one image (thumb_image or banner_image) above function is worked properly.
But when I upload both images thumb_image uploaded properly but banner_image did not upload properly. As a example assume I am going to upload Hydrangeas.jpg and Desert.jpg. Then it is working this way,
Then file uploaded this way (images names of the folder),
1493025280_Hydrangeas.jpg
1493025280_Hydrangeas_thumb.jpg
1493025280_Hydrangeas1.jpg - image name also wrong
But expected output is (images names of the folder),
1493025280_Hydrangeas.jpg
1493025280_Hydrangeas_thumb.jpg
1493025280_Desert.jpg
1493025280_Desert_banner.jpg
Can someone please help me, thank you..
A different approach that i use for file uploads is below.
I rearrange the $_FILES array because the original has some difficulties with keys and objects.
$files = array();
foreach ($_FILES['files']['name'] as $num_key => $dummy) {
foreach ($_FILES['files'] as $txt_key => $dummy) {
$files[$num_key][$txt_key] = $_FILES['files'][$txt_key][$num_key];
}
}
In new array, loop through each image and do what you need:
foreach ($files as $file) {
if ($file['error'] == 0) {
//Your code here...
//Call your function imageUploadResize
}
}
Finally found the solution, In codeigniter when upload image, we have to call,
$this->load->library('upload', $config);
Then we have to initialized the configurations.
$this->upload->initialize($config);
And when resize image we have to call,
$this->load->library('image_lib', $config);
Then have to initialized the configurations.
$this->image_lib->initialize($config);
Therefore completed function is,
protected function imageUploadResize($filename, $field_name, $width, $height, $maker){
// thumb image upload settings
$config['upload_path'] = './uploads/packages/';
$config['allowed_types'] = 'gif|jpg|png';
// thumb upload settings
$image_new_name = time().'_'.$filename;
$config['file_name'] = $image_new_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
// upload thumb image
if ( $this->upload->do_upload($field_name)) {
// resize uploaded file
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/packages/'.$image_new_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['thumb_marker'] = $maker;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$error = array('error' => $this->upload->display_errors());
} else {
$imageData = array('upload_data' => $this->upload->data());
}
return $image_new_name;
}
my controller:
public function addgalleryProcess()
{
$height = $this->input->POST('height');
$width = $this->input->POST('width');
$config['upload_path'] = './assets/images/gallery';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/addgallery', $error);
}
else
{
$upload_data = $this->upload->data();
//resize:
$config1['image_library'] = 'gd2';
$config1['source_image'] = $upload_data['full_path'];
$config1['maintain_ratio'] = TRUE;
$config1['create_thumb'] = TRUE;
$config1['width'] = $width;
$config1['height'] = $height;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
$this->adminModel->galleryimages($upload_data);
$this->load->view('admin/homeView');
}
my model:
public function galleryimages($image_data = array())
{
$data = array(
'image' => $image_data['file_name'],
);
$this->db->insert('gallery', $data);
}
Here image is uploaded properly and working, but resize is not working. I have to display the resized image with specified width and height. I am new to this.
Thanking in advance.
Try this:
For image resize I suggest to use "TimThumb" TimThumb – PHP Image Resizer
https://www.binarymoon.co.uk/projects/timthumb/
I have use timthumb in my project like
<img src="<?php echo base_url('assets/common/timthumb') . '/timthumb.php?src=./assets/myuploads/myimagename.jpg&w=245&h=164'; ?>" alt="">
I have put timthumb.php in "assets" folder and I uploaded my images in "assets/myuploads" folder
Not to be to distracting, if you want to resize the image before upoading through the networks, you can javascript it to a canvas and then send the canvas image in toDataURL. This would help prevent someone from uploading something massive and your network and server struggle with it.
This also depends if your client in a HTML client.
The following Article can help with this,:
https://stackoverflow.com/a/10334170/811827
I am trying to create a profile thumbnail for user when he upload a profile picture. I amlooking from some assistance here as recently put my hand on Codeiniter and I am new to php too.
Currently this inserts the profile image to 'temp' folder but doesn't resize it. I may be doing it wrong. Do I have to create a new function for thumbnail or I can include it along with the one I have?
I have no problem with adding a new profile picture. replacing the picture and deleting the profile picture automatically when new one is added. Just the resizing(thumbnail) of image.
Here is controller:
public function profile_image() {
if($this->session->userdata('is_logged_in')){
$username = $this->session->userdata('v_member_username');
$url1 = $this->my_profile_model->see_if_old_image_exists($username);
if (empty($_FILES['profile_image']['tmp_name'])) {
return true;
}else{
$url2 = $this->do_upload();
$this->my_profile_model->update_profile_image($url2, $username);
if(!empty($url1)){
$this->my_profile_model->delete_old_profile_image($url1);
}
}
}
}
private function do_upload() {
$type = explode('.', $_FILES['profile_image']['name']);
$type = $type[count($type)-1];
$filename = uniqid(rand()).'.'.$type;
$url2 = './uploads/temp/'.$filename;
if(in_array($type, array('jpeg', 'gif', 'png', 'jpg')))
if (empty($_FILES['profile_image']['tmp_name'])) {
return TRUE;
}else{
if(is_uploaded_file($_FILES['profile_image']['tmp_name']))
if(move_uploaded_file($_FILES['profile_image']['tmp_name'], $url2));
return $url2;
return '';
// do_thumb
$this->load->library('image_lib');
$source_path = $_SERVER['DOCUMENT_ROOT'] . 'uploads/temp/' . $filename;
$target_path = $_SERVER['DOCUMENT_ROOT'] . 'uploads/profile/';
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'create_thumb' => TRUE,
'thumb_marker' => '_thumb',
'width' => 270,
'height' => 263
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear //
$this->image_lib->clear();
}
}
And my model is:
// Update profile Image
function update_profile_image($url2, $username){
$this->db->set('profile_image', $url2);
$this->db->where('v_member_username', $username);
$this->db->update('vbc_registered_members');
}
// Look If There Was Any Old Image Earlier
function see_if_old_image_exists($username) {
$this->db->select('profile_image');
$this->db->from('vbc_registered_members');
$this->db->where('v_member_username', $username);
$query = $this->db->get();
$query_result = $query->result();
$row = $query_result[0];
return $row->profile_image;
}
// Auto Delete profile Image From Upload Folder On Updating New Image
function delete_old_profile_image($url1) {
unlink($url1);
return TRUE;
}
Please advise.
Codeigniter provides a library for uploading data.
see File Upload Library and Image Library
This is the code I use for uploading images, creating a thumbnail + resizing the image
/*
* This function returns the path of imagemagick on your system
*/
public static function getLibPath()
{
if(strlen(self::$_lib_path)==0)
{
self::$_lib_path=exec("/bin/bash -lc '/usr/bin/which convert'",$out,$rcode);
}
return self::$_lib_path;
}
/*
* This function handles the upload and calls the resizeImage function
* to generate the thumbnail and the resized image
*/
public function update()
{
$config['upload_path'] = 'your upload path';
$config['allowed_types'] = 'jpg|png|bmp';
$config['max_size'] = '8192';//8mb //4096kb - 4mb
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = false;
$config['encrypt_name']=true;//this generates a filename for you
$this->load->library('upload', $config);
$result = $this->upload->do_upload();
if($result) {
$fileInfo=$this->upload->data();
$this->resizeImage($fileInfo['full_path']);
$data = array(
'filename' => $fileInfo['file_name'],
'orig_file_name' =>$fileInfo['orig_name'],
);
//pseudo function for storing the file info
save_metadata_to_db($data);
}
else
{
echo $this->upload->display_errors());
}
}
/*
* This function creates a thumbnail + the resized image
*/
private function resizeImage($filename)
{
//This function creates a file with the orig. filename + _thumb
$config['image_library'] = 'ImageMagick';
$config['source_image'] = $filename;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 60;
$config['height'] = 60;
$config['library_path'] = $this->getLibPath();
$config['quality'] = '100%';
$this->load->library('image_lib', $config);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors());
}
$config['create_thumb'] = False;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1080;
$config['height'] = 1920;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors());
}
}
I am trying to create an upload folder for each user on my site, and display their photos in a specific area. I have been able to get the codeigniter upload helper to work and can upload files to a folder. Now I want to be able to:
have the photos upload by a specific user be placed in a folder for that user created on the fly specific to their id
auto size the photo for two sizes. A thumbnail and a larger size
I think I have it set up from research on how to do those things I just don't know how to plug in their id's syntactically as well as creating a folder and uploading it.
the last step would be displaying these photos in the locations of my choice tied to their ids.
Here is my controller
public function upload()
{
mkdir('./upload/' . $this->session->userdata('id'), 0777);
$config['image_library'] = 'gd2';
$config['source_image'] = 'PATH TO FOLDER??';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$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());
$data['main_content'] = 'account/upload';
$this->load->view('includes/templates/main_page_template', $data);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
You're creating the users directory but not setting it as the upload path...
$user_folder = './upload/' . $this->session->userdata('id');
if(!is_dir($user_folder)){
mkdir($user_folder, 0777);
}
...
$config['upload_path'] = $user_folder;
....