Hi I was wondering if you could help me, basically I am using Codeigniter and I want to be able to upload an image and save it to three different folders as three different sizes, however, they must fit the exact dimensions I specify without looking stretched or distorted.
This is my controller - if you could help me I would be most grateful.
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$this->load->library('upload');
$this->upload->initialize($config);
if(!$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('submit', $error);
}
else {
$data['upload_data'] = array('upload_data' => $this->upload->data());
$file_name = $this->upload->file_name;
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name);
// create small size
$config['image_library'] = 'GD2';
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name;
$config['new_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name;
$config['maintain_ratio'] = TRUE;
$config['width'] = 181;
$config['height'] = 115;
$config['master_dim'] = 'width';
$this->load->library('image_lib');
$this->image_lib->initialize($config);
if($image_width >= $config['width'] AND $image_height >= $config['height'])
{
if (!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
} else {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name))
{
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name);
if($image_height > '115')
{
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name;
$y_axis = $image_height - 115;
$config['y_axis'] = $y_axis;
$config['x_axis'] = 181;
$this->image_lib->initialize($config);
if (!$this->image_lib->crop())
{
echo $this->image_lib->display_errors();
} else {
echo "cropped";
}
}
}
}
}
I'm not sure if you were having trouble getting the actual image sizer library to work, or whether you just want to know how to save to three different places with different sizes... assuming you want to do the latter, you probably want to just create a function that does the image sizing stuff for you and then pass in the different height/width/name of directory/etc. that you want... Haven't tested it but it would look something like this:
function your_function() {
$this->upload->initialize($config);
$this->load->library('upload');
$this->load->library('image_lib');
if(!$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('submit', $error);
}
else
{
$data['upload_data'] = array('upload_data' => $this->upload->data());
$file_name = $this->upload->file_name;
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name);
$this->image_resize('115', '181', 'small', $file_name, $image_width, $image_height);
$this->image_resize('300', '400', 'medium', $file_name, $image_width, $image_height);
$this->image_resize('600', '500', 'large', $file_name, $image_width, $image_height);
}
}
private function image_resize($height, $width, $path, $file_name, $image_width, $image_height)
{
// Resize image settings
$config['image_library'] = 'GD2';
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name;
$config['new_image'] = $_SERVER['DOCUMENT_ROOT']."/website/uploads/$path/$file_name";
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['master_dim'] = 'width';
$this->image_lib->initialize($config);
if($image_width >= $config['width'] AND $image_height >= $config['height'])
{
if (!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
} else {
if(file_exists($_SERVER['DOCUMENT_ROOT']."/website/uploads/$path/$file_name"))
{
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT']."/website/uploads/$path$file_name");
if($image_height > '115')
{
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name;
$y_axis = $image_height - 115;
$config['y_axis'] = $y_axis;
$config['x_axis'] = 181;
$this->image_lib->initialize($config);
if (!$this->image_lib->crop()){
echo $this->image_lib->display_errors();
} else {
echo "cropped";
}
}
}
}
}
}
Related
How to resize the news picture? I never could.
My problem [source_image]
I use Codeigniter 3.1.6
Controller
public function insert_news() {
$config['upload_path'] = 'uploads/news/';
$config['allowed_types'] = 'gif|jpg|png';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('news_image'))
{
$image = $this->upload->data();
$image_url = $image['file_name'];
$db_insert ='upload/news/'.$image_url.'';
$data=array(
'news_title' => $this->input->post('news_title'),
'news_content' => $this->input->post('news_content'),
'news_image' => $db_insert,
'news_sef'=>sef($this->input->post('news_title'))
);
$this->load->model('vt');
$result = $this->vt->insert_news($data);
if ($result) {
echo "yes";
} else {
echo "no";
}
}
}
You can try this solution for your problem :
Controller :
<?php
public function insert_news() {
$config['upload_path'] = 'uploads/news/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20240000245';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = TRUE;
// You can change width & height
$imgage_width= 60;
$imgage_height= 60;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload($field)) {
$error = $this->upload->display_errors();
// uploading failed. $error will holds the errors.
$this->form_validation->set_message('error',$error);
return FALSE;
} else {
$fdata = $this->upload->data();
$configer = array(
'image_library' => 'gd2',
'source_image' => $fdata['full_path'],
'maintain_ratio' => TRUE,
'width' => $imgage_width,
'height' => $imgage_height,
);
// Load Image Lib Library
$this->load->library('image_lib');
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
$img_data ['path'] = $config['upload_path'] . $fdata['file_name'];
// uploading successfull, now do your further actions
$data=array(
'news_title' => $this->input->post('news_title'),
'news_content' => $this->input->post('news_content'),
'news_image' => $img_data ['path'],
'news_sef'=>sef($this->input->post('news_title'))
);
$this->load->model('vt');
$result = $this->vt->insert_news($data);
if ($result) {
$this->form_validation->set_message('success',"News has been added successfully.");
redirect('contorller/action_name');
} else {
$this->form_validation->set_message('error',"Error in aading news");
redirect('contorller/action_name');
}
}
}
?>
I Hope it will Help you.
I want to upload multiple images using two file input as well as resize them.
1. original image
2. 100 x 100
3. 400 x 200
All works fine but image lib not resize properly.It uploads images in original size.I have check following things.
1. Image lib load only once. which i load in __construct().
2. before initializing clear the image lib. $this->image_lib->clear();
function do_upload($name,$shop_code) {
$files = $_FILES;
if ($name == 'pre_photo_array') {
$photo_name = 'pre_photo_array';
} else {
$photo_name = 'post_photo_array';
}
$cpt = count($_FILES[$name]['name']);
--$cpt;
for ($i = 0; $i < $cpt; $i++) {
$_FILES[$photo_name]['name'] = $files[$photo_name]['name'][$i];
$_FILES[$photo_name]['type'] = $files[$photo_name]['type'][$i];
$_FILES[$photo_name]['tmp_name'] = $files[$photo_name]['tmp_name'][$i];
$_FILES[$photo_name]['error'] = $files[$photo_name]['error'][$i];
$_FILES[$photo_name]['size'] = $files[$photo_name]['size'][$i];
if ($photo_name == 'pre_photo_array') {
$config['upload_path'] = './assets/images/shop_images/pre_pic/';
} else {
$config['upload_path'] = './assets/images/shop_images/post_pic/';
}
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
$config['file_name'] = $shop_code.'_'.time();
$this->upload->initialize($config);
if (!$this->upload->do_upload($photo_name)) {
$error = array('error' => $this->upload->display_errors());
$file_path[] = ' ';
} else {
$upload_data = $this->upload->data();
if ($name == 'pre_photo_array') {
$imgdata=exif_read_data('assets/images/shop_images/pre_pic/'.$upload_data['file_name'], 'IFD0');
$source_image_path = getimagesize('assets/images/shop_images/pre_pic/'.$upload_data['file_name']);
$source_image = 'assets/images/shop_images/pre_pic/'.$upload_data['file_name'];
$Pre_Thumbnail_new_image = 'assets/images/shop_images/pre_pic/Thumbnail/'.$upload_data['file_name'];
$Pre_ppt_new_image = 'assets/images/shop_images/pre_pic/PPT/'.$upload_data['file_name'];
} else {
$imgdata=exif_read_data('assets/images/shop_images/post_pic/'.$upload_data['file_name'], 'IFD0');
$source_image_path = getimagesize('assets/images/shop_images/post_pic/'.$upload_data['file_name']);
$source_image = 'assets/images/shop_images/post_pic/'.$upload_data['file_name'];
$Post_Thumbnail_new_image = 'assets/images/shop_images/post_pic/Thumbnail/'.$upload_data['file_name'];
$Post_ppt_new_image = 'assets/images/shop_images/post_pic/PPT/'.$upload_data['file_name'];
}
$rotation_angle = 0;
switch(isset($imgdata['Orientation'])) {
case 3:
$rotation_angle='180';
break;
case 6:
$rotation_angle='90';
break;
case 8:
$rotation_angle='90';
break;
}
if($name == 'pre_photo_array') {
$Thumbnail_new_image = $Pre_Thumbnail_new_image;
$ppt_new_image = $Pre_ppt_new_image;
} else {
$Thumbnail_new_image = $Post_Thumbnail_new_image;
$ppt_new_image = $Post_ppt_new_image;
}
// Create Thumbnail
$Thumbnail['image_library'] = 'gd2';
$Thumbnail['source_image'] = $source_image;
$Thumbnail['new_image'] = $Thumbnail_new_image;
$Thumbnail['create_thumb'] = TRUE;
$Thumbnail['thumb_marker'] = FALSE;
$Thumbnail['maintain_ratio'] = TRUE;
$Thumbnail['width'] = 100;
$Thumbnail['height'] = 100;
$Thumbnail['rotation_angle'] = $rotation_angle;
$this->image_lib->clear();
$this->image_lib->initialize($Thumbnail);
// resize image
$this->image_lib->resize();
$this->image_lib->rotate();
// handle if there is any problem
if(!$this->image_lib->resize()) {
echo "if";
echo $this->image_lib->display_errors();exit;
}
if($source_image_path[0] > $source_image_path[1]){
$width = 400;
$height = 200;
}else{
$width = 200;
$height = 400;
}
// Create PPt image
$ppt['image_library'] = 'gd2';
$ppt['source_image'] = $source_image;
$ppt['new_image'] = $ppt_new_image;
$ppt['create_thumb'] = FALSE;
$ppt['thumb_marker'] = FALSE;
$ppt['maintain_ratio'] = TRUE;
$ppt['width'] = 400;
$ppt['height'] = 200;
$ppt['rotation_angle']=$rotation_angle;
$this->image_lib->clear();
$this->image_lib->initialize($ppt);
// resize image
$this->image_lib->resize();
$this->image_lib->rotate();
// handle if there is any problem
if(!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();exit;
}
if($photo_name == 'pre_photo_array') {
$path = 'assets/images/shop_images/pre_pic/';
} else {
$path = 'assets/images/shop_images/post_pic/';
}
$file_path[] = $path.$upload_data['file_name'];
}
}
return $file_path;
}
}
I am adding my Upload Image and Create Multiple Thumbnail Sizes in CodeIgniter Example. Hope it helps you.
//initialize the path where you want to save your images
function __construct(){
parent::__construct();
//return the full path of the directory
//make sure these directories have read and write permessions
$this->original_path = realpath(APPPATH.'../uploads/original');
$this->resized_path = realpath(APPPATH.'../uploads/resized');
$this->thumbs_path = realpath(APPPATH.'../uploads/thumbs');
}
function do_upload(){
$this->load->library('image_lib');
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png', //only accept these file types
'max_size' => 2048, //2MB max
'upload_path' => $this->original_path //upload directory
);
$this->load->library('upload', $config);
$image_data = $this->upload->data(); //upload the image
//your desired config for the resize() function
$config = array(
'source_image' => $image_data['full_path'], //path to the uploaded image
'new_image' => $this->resized_path, //path to
'maintain_ratio' => true,
'width' => 128,
'height' => 128
);
//this is the magic line that enables you generate multiple thumbnails
//you have to call the initialize() function each time you call the resize()
//otherwise it will not work and only generate one thumbnail
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->thumbs_path,
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
//here is the second thumbnail, notice the call for the initialize() function again
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}
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.
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',
);
When I crop an image it turns completely black?? Why??
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'; $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$this->load->library('upload'); $this->upload->initialize($config);
if(!$this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view('submit', $error); } else { $data['upload_data'] = array('upload_data' => $this->upload->data()); $file_name
= $this->upload->file_name;
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name);
// create small size $config['image_library'] = 'GD2'; $config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/original/'.$file_name; $config['new_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name; $config['maintain_ratio'] = TRUE; $config['width'] = 181; $config['height'] = 115; $config['master_dim'] = 'width';
$this->load->library('image_lib'); $this->image_lib->initialize($config);
if($image_width >= $config['width'] AND $image_height >= $config['height']) {
if (!$this->image_lib->resize())
{
echo $this->image_lib->display_errors();
} else {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name))
{
list($image_width, $image_height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name);
if($image_height > '115')
{
$config['source_image'] = $_SERVER['DOCUMENT_ROOT'].'/website/uploads/small/'.$file_name;
$y_axis = $image_height - 115;
$config['y_axis'] = $y_axis;
$config['x_axis'] = 181;
$this->image_lib->initialize($config);
if (!$this->image_lib->crop())
{
echo $this->image_lib->display_errors();
} else {
echo "cropped";
}
}
} } }
I believe CI uses the standard PHP GD module. Previously I've found that if the image you're using is slightly corrupt it will still display normally but once you resize you simply get a black box.
Have you tried using any other images? Images of different types (png/jpg/etc)?