I am developing a web application. In my application, I am uploading an image to server and then resize it. I uploaded to server successfully. But when I resize image, it is not resizing image. But it is not throwing error as well.
This is my image file upload model
class file_helper extends CI_Model{
function __construct()
{
parent::__construct();
$this->load->library('image_lib');
}
function generateRandomFileName()
{
$rand = rand(10000,99999);
$file_name = time().$rand;
return time().$rand;
}
function uploadImage()
{
$name = $this->generateRandomFileName();
$config['upload_path'] = './'.UPLOAD_FOLDER.'/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $name;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile'))
{
return FALSE;
}
else
{
$data = $this->upload->data();
$data['virtual_path'] = UPLOAD_FOLDER."/".$name.".".$data['file_ext'];
return $data;
}
}
function resizeImage($path)
{
$config['image_library'] = 'gd2';
$config['source_image'] = '/'.$path;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 300;
$config['height'] = 50;
$this->load->library('image_lib', $config);
if ( ! $this->image_lib->resize())
{
print_r($this->image_lib->display_errors());
}
else{
echo "Ok";
}
}
}
As you can see in the model I print out "Ok" on success and print_r the error in failure. The path I passed is something like this "uploads/23344545.png". But that resize function always print out "Ok", but the image is not resized. What is wrong with my code?
You need to resize the image while uploading
function uploadImage()
{
$name = $this->generateRandomFileName();
$config['upload_path'] = './'.UPLOAD_FOLDER.'/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $name;
$config['width'] = 300;
$config['height'] = 50;
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile'))
{
return FALSE;
}
else
{
$data = $this->upload->data();
$data['virtual_path'] = UPLOAD_FOLDER."/".$name.".".$data['file_ext'];
return $data;
}
}
Related
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;
}
I want to write a php code for resizing images that are retrieved from database and upload it in the site. But i can't resize the images. That are directly uploaded into site without resize.. My code is given below ..thanks in advance ...
public function editimg()`enter code here`
{
$config['image_library'] = 'gd2';
$id=$this->input->post('hiddenimgid');
$config['upload_path'] = './assets/img/movies';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '150';
$config['max_width'] = '199';
$config['max_height'] = '199';
//echo "hii";die;
// print_r($config);die;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//echo "not uploaded";die;
$error = array('error' => $this->upload->display_errors());
$data['message'] = "Image Cannot be Uploaded,Try Again !!";
$data['error']=$error;
$this->index_one($data);
} //if
else
{
//echo "hii";die;
$config['image_library'] = 'gd2';
$image_data = $this->upload->data();
$filename = $image_data['file_name'];
$source_path = 'assets/img/movies/'.$filename ;
$new_image_path = 'assets/img/movies/'.$image_data['raw_name'].'_thumb'.$image_data['file_ext']; //name of resized image
$target_path = 'assets/img/movies/';
$thumb['image_library'] = 'gd2';
$thumb['source_image'] = $source_path;
$thumb['new_image'] = $target_path;
$thumb['create_thumb'] = TRUE;
$thumb['maintain_ratio'] = TRUE;
$thumb['width'] = 140;
$thumb['height'] = 200;
//print_r($thumb);die;
//$this->load->library('image_lib', $config);
$this->load->library('image_lib', $thumb);
if ( !$this->image_lib->resize())
{
//echo "hii";die;
//$this->session->set_flashdata('errors', $this->image_lib->display_errors('', ''));
$this->session->set_flashdata('errors', $error= $this->image_lib->display_errors('', ''));
print_r($error);die;
}
else
{
//echo "hii";die;
//print_r($thumb);die;
$data=array(
'image'=>$new_image_path
);
//print_r($new_image_path);die;
if($this->movies_model->updateMovies($data,$id))
{
$data['message'] = "Movies added successfully !!";
//$this->index_one($data);
redirect("movies/index", 'refresh');
//print_r($thumb);die;
}
else
{
$data['message'] = "not_uploaded !!";
$this->index_one($data);
}
}
}
}
`
It simple to use Simple image
<?php
include('src/abeautifulsite/SimpleImage.php');
try {
$img = new abeautifulsite\SimpleImage('/*image name*/');
$img->resize(320, 200)->save('/*name of resize image*/');resize image and save resized image
} catch(Exception $e) {
echo 'Error: ' . $e->getMessage();
}
Oleh is correct, if you're struggling with image resizing it's best to use a library to handle all the edge cases and gotchas.
Here's how to do it with SimpleImage 2.x:
$image = new \abeautifulsite\SimpleImage('image.jpg');
$image->resize(320, 200)->save('result.jpg');
And SimpleImage 3.x:
$image = new \claviska\SimpleImage('image.jpg');
$image->resize(320, 200)->toFile('output.jpg');
The SimpleImage library can be installed with Composer:
composer require claviska/simpleimage
Or downloaded from GitHub and included manually.
I am using default library of codeigniter to resize my image to get different thumbs. I have refer to Documentation of codeigniter for this.
My images gets resize fine. Now, I want to store resized image path in database. For that I checked library file and other details as well but not found a way to get resized image path.
Please check my code
protected function createThumbs($params)
{
if( !is_dir($params['targetPath']) ) {
mkdir($params['targetPath'], 0777, TRUE);
}
$tConfig['image_library'] = 'gd2';
$tConfig['source_image'] = $params['sourcePath'];
$tConfig['new_image'] = $params['targetPath'];
$tConfig['create_thumb'] = TRUE;
$tConfig['maintain_ratio'] = TRUE;
$tConfig['width'] = $params['width'];
$tConfig['height'] = $params['height'];
$this->load->library('image_lib', $tConfig);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear //
$this->image_lib->clear();
}
Does anyone knows how to get it?
Try
protected function createThumbs($params)
{
if( !is_dir($params['targetPath']) ) {
mkdir($params['targetPath'], 0777, TRUE);
}
$tConfig['image_library'] = 'gd2';
$tConfig['source_image'] = $params['sourcePath'];
$tConfig['new_image'] = $params['targetPath'];
$tConfig['create_thumb'] = TRUE;
$tConfig['maintain_ratio'] = TRUE;
$tConfig['width'] = $params['width'];
$tConfig['height'] = $params['height'];
$this->load->library('image_lib', $tConfig);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear
$this->image_lib->clear();
#return
$file_info = pathinfo($tConfig['new_image']);
return $file_info['dirname'].'/'.$file_info['filename'].'_thumb.'.$file_info['extension'];
}
Your thumb file will be called with _thumb at the end of file name.
For example if your file is: image.jpg your resized thumb will be called image_thumb.jpg
public function addUserImages()
{
$image = preg_replace("/\s+/", "_", $_FILES['user_image']['name']);
$config['upload_path'] = "./Images/ProfileImages/";
$config['allowed_types'] = "gif|jpg|png|jpeg|JPG|JPEG|PNG|GIF";
$config['file_name'] = $image;
$this->load->library('upload',$config);
if($this->upload->do_upload("user_image")==false)
{
$error = array('error' => $this->upload->display_errors());
echo $error['error'];
return $error->error;
}
else
{
$data = $this->upload->data();
$newImage = $data['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = './Images/ProfileImages/'.$newImage;
$config['new_image'] = './Images/ProfileImages/small_'.$newImage;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['quality'] = '100';
$config['width'] = 250;
$config['height'] = 250;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
if(!$this->image_lib->resize())
{
return $this->image_lib->display_errors();
}
else {
$newImage = "small_".$newImage;
}
}
}
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 upload multiple images(3) at a time and create thumbnail for each image. But my code upload 3 images and create only 1 thumbnail(thumbnail of 1st image). How to create thumbnail of multiple images?
Controller: uploadImage function and create thumbnail function
function uploadImage()
{
if($this->validate()==TRUE) {
$config['upload_path'] = "images/uploads/";
$config['allowed_types'] = "gif|jpg|jpeg|png";
$config['max_size'] = "5000";
$config['max_width'] = "1907";
$config['max_height'] = "1280";
$this->load->library('upload', $config);
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name'])) {
if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
}
else {
//success
$finfo=$this->upload->data();
$this->_createThumbnail($finfo['file_name']);
$data['uploadInfo'] = $finfo;
$data['thumbnail_name'] = $finfo['raw_name']. '_thumb' .$finfo['file_ext'];
}
}
}
}
}
//Create Thumbnail function
function _createThumbnail($filename)
{
$config['image_library'] = "gd2";
$config['source_image'] = "images/uploads/" .$filename;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = "80";
$config['height'] = "80";
$this->load->library('image_lib',$config);
if(!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
}
Do some changes in createthumbnail function according to this link.
Instead of
$this->load->library('image_lib',$config);
use
$this->load->library('image_lib');
// Set your config up
$this->image_lib->initialize($config);
// Do your manipulation
$this->image_lib->clear();
New createThumbnail function:
//Create Thumbnail function
function _createThumbnail($filename)
{
$this->load->library('image_lib');
// Set your config up
$config['image_library'] = "gd2";
$config['source_image'] = "images/uploads/" .$filename;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = "80";
$config['height'] = "80";
$this->image_lib->initialize($config);
// Do your manipulation
if(!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
}