I'm new to programming and require some help regarding the below issue.
I have the below script that I guess controls the upload of the image.
Is there any easy way to add a autoresizer of the image to 1024x768?
public function index()
{
$validator = Validator::make(Input::all(), [
'image' => 'required|image|max:' . (1024 * 3),
]);
if ($validator->fails()) {
$messages = $validator->messages();
echo json_encode([
'return' => 'error',
'message' => $messages->first('image')
]);
} else {
$originalName = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$size = Input::file('image')->getSize();
$type = (Auth::check()) ? Auth::user()->default_image_privacy : 'public';
$adult = Input::has('adult') ? Input::get('adult') : 0;
$adult = ($adult != 1) ? 0 : 1;
$status = (Settings::get('auto_approve_images') == 1) ? 'active' : 'pending';
$image = new Image;
$image->user_id = (Auth::check()) ? Auth::user()->id : 0;
$image->file_name = $originalName;
$image->file_extn = $extension;
$image->file_size = $size;
$image->status = $status;
$image->type = $type;
$image->adult = $adult;
$image->ip = Net::getIP();
$image->save();
$imageFolder = floor($image->id / 1000) + 1;
$imageFolder = md5($imageFolder);
$imageFolder = substr($imageFolder, 1, 10);
$imageFolder = trim($imageFolder);
$image->folder = $imageFolder;
$image->save();
$destinationPath = public_path('uploads/' . $imageFolder);
$fileName = $image->id . '.' . $extension;
Input::file('image')->move($destinationPath, $fileName);
$destinationPathThumb = public_path('thumb/' . $imageFolder);
if (! File::isDirectory($destinationPathThumb)) {
File::makeDirectory($destinationPathThumb, 0755, true);
}
$fileNameThumb = $image->id . '.' . $extension;
$thumbWidth = (int) Settings::get('thumb_width');
$thumbWidth = ($thumbWidth < 80) ? 100 : $thumbWidth;
$thumbHeight = (int) Settings::get('thumb_height');
$thumbHeight = ($thumbHeight < 80) ? 100 : $thumbHeight;
Thumb::create($destinationPath . '/' . $fileName, $destinationPathThumb . '/' . $fileNameThumb, $thumbWidth, $thumbHeight);
$fileNameMed = $image->id . '_md.' . $extension;
$medWidth = 700;
$medHeight = 600;
Thumb::create($destinationPath . '/' . $fileName, $destinationPathThumb . '/' . $fileNameMed, $medWidth, $medHeight);
echo json_encode([
'return' => 'success',
'imageUid' => $image->id
]);
}
exit();
}
public function link()
{
$validator = Validator::make(Input::all(), [
'url' => 'required|url',
]);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
} else {
$originalName = basename(Input::get('url'));
$nameSplit = explode('.', $originalName);
$extension = $nameSplit[count($nameSplit) - 1];
if (! in_array($extension, ['jpeg', 'jpg', 'png', 'bmp', 'gif'])) {
return Redirect::back()->withErrors($validator);
}
$type = (Auth::check()) ? Auth::user()->default_image_privacy : 'public';
$adult = Input::has('adult') ? Input::get('adult') : 0;
$adult = ($adult != 1) ? 0 : 1;
$image = new Image;
$image->user_id = (Auth::check()) ? Auth::user()->id : 0;
$image->file_name = $originalName;
$image->file_extn = $extension;
$image->status = 'active';
$image->type = $type;
$image->adult = $adult;
$image->ip = Net::getIP();
$image->save();
$imageFolder = floor($image->id / 1000) + 1;
$imageFolder = md5($imageFolder);
$imageFolder = substr($imageFolder, 1, 10);
$imageFolder = trim($imageFolder);
$image->folder = $imageFolder;
$image->save();
$destinationPath = public_path('uploads/' . $imageFolder);
$fileName = $image->id . '.' . $extension;
File::copy(Input::get('url'), $destinationPath . '/' . $fileName);
$size = File::size($destinationPath . '/' . $fileName);
$image->file_size = $size;
$image->save();
$destinationPathThumb = public_path('thumb/' . $imageFolder);
if (! File::isDirectory($destinationPathThumb)) {
File::makeDirectory($destinationPathThumb, 0755, true);
}
$fileNameThumb = $image->id . '.' . $extension;
$thumbWidth = (int) Settings::get('thumb_width');
$thumbWidth = ($thumbWidth < 80) ? 100 : $thumbWidth;
$thumbHeight = (int) Settings::get('thumb_height');
$thumbHeight = ($thumbHeight < 80) ? 100 : $thumbHeight;
Thumb::create($destinationPath . '/' . $fileName, $destinationPathThumb . '/' . $fileNameThumb, $thumbWidth, $thumbHeight);
$fileNameMed = $image->id . '_md.' . $extension;
$medWidth = 700;
$medHeight = 600;
Thumb::create($destinationPath . '/' . $fileName, $destinationPathThumb . '/' . $fileNameMed, $medWidth, $medHeight);
return Redirect::to('/upload/success?id=' . $image->id);
}
}
public function success()
{
if (! Input::has('id')) {
return Redirect::to('/');
}
$imageIdArr = explode(',', Input::get('id'));
$imageIdArr = array_where($imageIdArr, function($key, $value)
{
return is_numeric($value);
});
$imageIdArr = array_unique($imageIdArr);
if (empty($imageIdArr)) {
return Redirect::to('/');
}
$imagesInfo = Image::whereIn('id', $imageIdArr)->get();
return View::make('upload.success', [
'imagesInfo' => $imagesInfo,
]);
}
You can resize the image with some fileuploader in the client side, you also can use server side tools such as imagemagic with command like this:
`convert $original_path -resize '1024x768^' -gravity Center -crop '1024x768+0+0' $resized_path`;
Related
Laravel Newbie here, would like to ask how to upload multiple images one by one. Multiple images work in one selection but putting images one by one to upload doesn't work and the first image only appears after submitting. Please help.
CONTROLLER
if (\Input::file('photos')) {
$base_path =
dirname(__FILE__) . "/../../../../uploads/img/gallery/" . $add->id . "/";
ini_set('gd.jpeg_ignore_warning', 1);
//get last uploaded file name
$files = (\Input::file('photos'));
$list_image = $temp = explode(",", $request->list_image);
foreach ($files as $key => $value) {
if (!is_null($value)) {
$temp = explode(".", $value->getClientOriginalName());
$newfilename = $value->getClientOriginalName();
if (!file_exists($base_path)) {
mkdir($base_path);
chmod($base_path, 0777);
}
$key = array_search($newfilename, $list_image);
if ($key == 0) {
$newfilename = $add->id . '_primary' . '.' . end($temp);
} else {
$newfilename = chr(64 + $key) . '_' . $newfilename;
}
$image = \Image::make($value);
// perform orientation using intervention
$image->orientate();
$new_width = $image->width();
$new_height = $image->height();
if ($new_width > 800) {
$percent = 0.7;
$new_width = $new_width * $percent;
$new_height = $new_height * $percent;
}
// resize image to fixed size
$image->resize($new_width, $new_height);
// create a new Image instance for inserting
$watermark = \Image::make(
public_path() . '/assets/img/icons/watermark.png',
);
// insert watermark at bottom-right corner with 10px offset
$image->insert(
public_path() . '/assets/img/icons/watermark.png',
'bottom-right',
10,
10,
);
$image->save($base_path . $newfilename);
}
}
}
You can do something like this.
$list_image = $temp = explode(",", $request->list_image);
if($request->hasfile('photos'))
{
$destinationPath = public_path('uploads/img/gallery/'. $add->id.'/');
foreach($request->file('photos') as $k => $file)
{
$temp = explode(".", $file->getClientOriginalName());
$newfilename = $file->getClientOriginalName();
$key = array_search($newfilename, $list_image);
if ($key == 0) {
$newfilename = $add->id . '_primary' . '.' . end($temp);
} else {
$newfilename = chr(64 + $key) . '_' . $newfilename;
}
$name = $newfilename.'.'.$file->getClientOriginalExtension();
File::makeDirectory($destinationPath, $mode = 0777, true, true);
$file->move($destinationPath, $name);
$tdestinationPath = public_path('uploads/img/gallery/thumb'. $add->id.'/');
try {
$img = Image::make($file->getRealPath());
$img->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
})->save($tdestinationPath.'/'.$name);
$img->destroy();
} catch (Exception $e) {
$response_data=array('images'=>"",'success'=>0,'message'=>$e->getMessage());
}
$image_arr[] = $name;
}
$uploaded_img = implode(',',$image_arr);
if(!empty($hidden_property_img)){
$uploaded_img = $hidden_property_img.','.$uploaded_img;
}
$data['images'] = $uploaded_img;
}
I am trying to update 'employee' and 'employee_details' in which I used one to one relationship. During the update, I am getting this error exactly in $employeeDetail->card_no = $request->card_no, in employeeDetail and I searched and tried to implement the possible solutions but still getting this error. Would someone help me to solve this problem, please?
EmployeeController.php
public function update(Request $request, $id)
{
$employee = Employee::find($id);
$employee->card_no = $request->card_no;
$employee->name = $request->name;
$employee->father_name = $request->father_name;
$employee->mother_name = $request->mother_name;
$employee->spouse_name = $request->spouse_name;
$employee->permanent_add = $request->permanent_add;
$employee->present_add = $request->present_add;
$employee->area = $request->area;
$employee->dob = Carbon::parse($request->dob)->format('Y-m-d');
$employee->blood_group = $request->blood_group;
$employee->nid_number = $request->nid_number;
$employee->mobile = $request->mobile;
$employee->reference_name = $request->reference_name;
$employee->reference_nid = $request->reference_nid;
$employee->reference_mobile = $request->reference_mobile;
$employee->reference_add = $request->reference_add;
if (! $request->photo == '') {
$employee->photo = $request->photo;
if ($file = $request->file('photo')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/photo';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old photo if exists
if (File::exists(public_path() . $folderName . $employee->photo)) {
File::delete(public_path() . $folderName . $employee->photo);
}
//save new file path into db
$employee->photo = $safeName;
}
}
if (! $request->nid_file == '') {
$employee->nid_file = $request->nid_file;
if ($file = $request->file('nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old nid_file if exists
if (File::exists(public_path() . $folderName . $employee->nid_file)) {
File::delete(public_path() . $folderName . $employee->nid_file);
}
//save new file path into db
$employee->nid_file = $safeName;
}
}
if (! $request->reference_nid_file == '') {
$employee->reference_nid_file = $request->reference_nid_file;
if ($file = $request->file('reference_nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old reference_nid_file if exists
if (File::exists(public_path() . $folderName . $employee->reference_nid_file)) {
File::delete(public_path() . $folderName . $employee->reference_nid_file);
}
//save new file path into db
$employee->reference_nid_file = $safeName;
}
}
if (! $request->character_file == '') {
$employee->character_file = $request->character_file;
if ($file = $request->file('character_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/character-certificate';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old character_file if exists
if (File::exists(public_path() . $folderName . $employee->character_file)) {
File::delete(public_path() . $folderName . $employee->character_file);
}
//save new file path into db
$employee->character_file = $safeName;
}
}
if ($employee->save()) {
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
return back()->with('success', 'Congratiolations! You appointed a new employee.');
}
}
Change
From
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
to
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
'card_no' => $request->card_no,
'section_id' => $request->section_id,
'designation_id' => $request->designation_id,
'salarygrade_id' => $request->salarygrade_id,
'joining_date' => Carbon::parse($request->joining_date)->format('Y-m-d'),
'quit_date' => $request->quit_date,
]);
Hello how can i include url function in photo
function photoUpload($file)
{
$messages = '';
$t = [];
$i = 0;
try {
$input = array(
'files' => $file,
'type' => Input::get('type'),
'max' => 1,
);
$files = array($input['files']);
$image = \Image::make($file->getRealPath());
$bigpath = public_path() . '/pictures/contentPhoto/big/';
$mediumpath = public_path() . '/pictures/contentPhoto/medium/';
$thumbpath = public_path() . '/pictures/contentPhoto/thumb/';
$maxFile = $input['max'];
$image->backup();
$rules = array('file' => 'max:50000|mimes:png,gif,jpeg,jpg');
if( !is_array($files) )
return ['status'=>false, 'msg'=> 'Bir problem var!' ];
if(count($files)>$maxFile)
return ['status'=>false, 'msg'=> 'En az bir fotoğraf gerekli!' ];
$status = array();
foreach ($files as $file) {
$isim = md5(uniqid('', true));
$t[]['org_name'] = $file->getClientOriginalName();
$t[$i]['extension'] = $file->getClientOriginalExtension();
$t[$i]['remote_name'] = $isim . '.' . $t[$i]['extension'];
$t[$i]['path'] = $thumbpath;
$t[$i]['remote_name'] = $isim . '.' . $file->getClientOriginalExtension();
$validator = Validator::make(array('file' => $file), $rules, [], ['file' => $file->getClientOriginalName()]);
if ($validator->passes()) {
$t[$i]['info'] = '<li>' . $file->getClientOriginalName() . ' bu fotoğraf yüklendi.' . '</li>';
$t[$i]['result'] = true;
$t[$i]['remote_full_name'] = Config::get('app.url') . '' . Config::get('app.pictures_db') . '/contentPhoto/thumb/' . $t[$i]['remote_name'];
$status[] = 1;
if (!file_exists(public_path().'/pictures/contentPhoto/')) {
mkdir(public_path().'/pictures/contentPhoto/', 0777, true);
}
$post_photo=$_FILES['files']['name'];
$post_photo_tmp=$_FILES['files']['tmp_name'];
$ext = pathinfo($post_photo, PATHINFO_EXTENSION); // getting image extension
list($width_min,$height_min)=getimagesize($post_photo_tmp); // fetching original image width and height
$ratio = $width_min / $height_min;
// Big Size
$newwidth_min=700; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$big = $image->resize($newwidth_min,$newheight_min);
$big->sharpen(18)->save($bigpath.$t[$i]['remote_name'],60);
$big->reset();
if($ratio < 1) {
$t[$i]['ratio'] = false;
// Medium Size
$newwidth_min=320; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$medium = $image->resize($newwidth_min,$newheight_min);
$medium->sharpen(8)->save($mediumpath.$t[$i]['remote_name'],60);
$medium->reset();
// Thumb Size
$newwidth_min=220; // set compressing image width
$newheight_min=($height_min / $width_min) * $newwidth_min; // equation for compressed image height
$thumb = $image->resize($newwidth_min,$newheight_min);
$thumb->sharpen(8)->save($thumbpath.$t[$i]['remote_name'],60);
$thumb->reset();
} else {
$t[$i]['ratio'] = true;
// Medium Size
$targetHeight= 320;
$targetWidth = 240;
$imgWidth = $image->getWidth();
$imgHeight = $image->getHeight();
$verticalRatio = $targetHeight / $imgWidth;
$horizontalRatio = $targetWidth / $imgHeight;
$imgAvg = min($verticalRatio,$horizontalRatio);
$newHeight = $imgHeight * $imgAvg;
$newWidth = $imgWidth * $imgAvg;
$medium = $image->resize($newWidth,$newHeight);
$medium->fit(320,170)->sharpen(8)->save($mediumpath.$t[$i]['remote_name'],60);
$medium->reset();
// Thumb Size
$targetHeight= 320;
$targetWidth = 240;
$imgWidth = $image->getWidth();
$imgHeight = $image->getHeight();
$verticalRatio = $targetHeight / $imgWidth;
$horizontalRatio = $targetWidth / $imgHeight;
$imgAvg = min($verticalRatio,$horizontalRatio);
$newHeight = $imgHeight * $imgAvg;
$newWidth = $imgWidth * $imgAvg;
$thumb = $image->resize($newWidth,$newHeight);
$thumb->fit(320,170)->sharpen(8)->save($thumbpath.$t[$i]['remote_name'],60);
$thumb->reset();
}
$insertDb = DBDosya::insertPicture($file->getClientOriginalName(), $isim.'.'.$file->getClientOriginalExtension(), '' . Config::get('app.pictures') . '/', '.'.$file->getClientOriginalExtension() );
$t[$i]['id'] = $insertDb;
} else {
$t[$i]['result'] = false;
$mesajlar = $validator->messages();
$htmlMesaj = '';
foreach ($mesajlar->all('<li>:message</li>') as $mesaj) {
$htmlMesaj .= $mesaj;
}
$t[$i]['info'] = $htmlMesaj;
}
$messages .= $t[$i]['info'];
$i++;
}
$status = in_array(1, $status);
} catch (Exception $e) {
return ['status' => false, 'msg' => $messages . '<li>' . $e->getMessage() . '</li>',];
}
return ['status' => $status, 'msg' => $messages, 'data' => $t[0]];
}
It works properly in the files that come with this file.
But I get getRealPath () error when I get photo with url.
How can I handle the photo from the URL with this function
Anyone can help me to set image max-size to 0.
Because I'm getting Error code: 1
Please help me to construct this code. I don't want to change the limit in php.ini Just want to know if there is a code solution for this problem:
function uploadPhoto()
{
$control = 'filephoto';
$path = './upload/';
$image = $_FILES[$control]['name'];
$size = $_FILES[$control]['size'];
if ($imageName = $this->doUpload($control, $path, $image, 'all')) {
} else {
}
}
function doUpload($control, $path, $imageName, $sizes)
{
if ($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$u_id = $session_data['u_id'];
$alnum = random_string('alnum', 16);
if ( ! isset($_FILES[$control]) || ! is_uploaded_file($_FILES[$control]['tmp_name'])) {
$this->session->set_flashdata('error_nofile', 'No file was chosen Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['size'] > 2048000) {
$this->session->set_flashdata('error_largefile', 'File is too large (' . round(($_FILES[$control]["size"] / 1000)) . 'kb), please choose a file under 2,048kb');
header('location:' . base_url() . "indexc/upload/");
return false;
}
if ($_FILES[$control]['error'] !== UPLOAD_ERR_OK) {
$this->session->set_flashdata('error_failed', 'Upload failed. Error code: ' . $_FILES[$control]['error']);
header('location:' . base_url() . "indexc/upload/");
Return false;
}
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES[$control]['tmp_name']);
move_uploaded_file($_FILES[$control]["tmp_name"], $path . $imageName);
break;
default:
$this->session->set_flashdata('error_notallowed', 'This file type is not allowed');
header('location:' . base_url() . "indexc/upload/");
return false;
}
#unlink($_FILES[$control]['tmp_name']);
$old_width = imagesx($image);
$old_height = imagesy($image);
//Create tn version
if ($sizes == 'tn' || $sizes == 'all') {
$max_width = 600;
$max_height = 600;
$scale = min($max_width / $old_width, $max_height / $old_height);
if ($old_width > 600 || $old_height > 600) {
$new_width = ceil($scale * $old_width);
$new_height = ceil($scale * $old_height);
} else {
$new_width = $old_width;
$new_height = $old_height;
}
$new = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
switch (strtolower($_FILES[$control]['type'])) {
case 'image/jpeg':
imagejpeg($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 90);
break;
case 'image/png':
imagealphablending($new, false);
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
imagesavealpha($new, true);
imagepng($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName, 0);
break;
case 'image/gif':
imagegif($new, $path . '' . $u_id . '_' . $alnum . '_' . $imageName);
break;
default:
}
}
imagedestroy($image);
imagedestroy($new);
/* print '<div style="font-family:arial;"><b>'.$imageName.'</b> Uploaded successfully. Size: '.round($_FILES[$control]['size']/1000).'kb</div>'; */
$this->session->set_flashdata('success_upload', '<div style="font-family:arial;"><b>' . $imageName . '</b> Uploaded successfully. Size: ' . round($_FILES[$control]['size'] / 1000) . 'kb</div>');
$postdata['p_u_id'] = $u_id;
$postdata['p_content'] = $this->input->post('content');
$postdata['p_image'] = $u_id . '_' . $alnum . '_' . $imageName;
$postdata['p_image_original'] = $imageName;
$postdata['p_posted'] = date("Y-m-d H:i:s");
$res = $this->indexm->postinsert_to_db($postdata);
header('location:' . base_url() . "indexc/upload/");
} else {
$this->load->view('index');
}
}
I also want to validate if the file type is jpg or png
Please help me!
thanks,
joe
try default codeigniter library :
function do_upload()
{
$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());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
I need your help to mix two function in my site. My purpose is to upload and resize the image.
I ve got one function doing the job fine for User picture, and i ve got another one for uploading picture (list or ads picture) but this function does not create thumb picture. it just upload it. What i like to do is to upload and resize like the function dedicated userpic.
Hope you can help me.
Here is the function concerning user picture ( thumb resize working)
public function photo($id = "") {
$target_path = realpath(APPPATH . '../images/users');
//echo $target_path;
if (!is_writable(dirname($target_path))) {
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error', 'Sorry! Destination folder is not writable.'));
redirect('users/edit', 'refresh');
} else {
if (!is_dir(realpath(APPPATH . '../images/users') . '/' . $id)) {
//echo $this->path.'/'.$id;
mkdir(realpath(APPPATH . '../images/users') . '/' . $id, 0777, true);
}
$target_path = $target_path . '/' . $id . '/userpic.jpg';
if ($_FILES['upload123']['name'] != '') {
move_uploaded_file($_FILES['upload123']['tmp_name'], $target_path);
$thumb1 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_thumb.jpg';
GenerateThumbFile($target_path, $thumb1, 107, 78);
$thumb2 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_profile.jpg';
GenerateThumbFile($target_path, $thumb2, 209, 209);
$thumb3 = realpath(APPPATH . '../images/users') . '/' . $id . '/userpic_micro.jpg';
GenerateThumbFile($target_path, $thumb3, 36, 36);
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('success', 'Your profile photo updated successfully.'));
redirect('users/edit', 'refresh');
} else {
$this->session->set_flashdata('flash_message', $this->Common_model->flash_message('error', 'Please browse your profile photo.'));
redirect('users/edit', 'refresh');
}
}
}
And here is the function i d like to implement the resize :
if ($this->input->post()) {
$listId = $param;
$images = $this->input->post('image');
$is_main = $this->input->post('is_main');
$fimages = $this->Gallery->get_imagesG($listId);
if ($is_main != '') {
foreach ($fimages->result() as $row) {
if ($row->id == $is_main)
$this->Common_model->updateTableData('list_photo', $row->id, NULL, array("is_featured" => 1));
else
$this->Common_model->updateTableData('list_photo', $row->id, NULL, array("is_featured" => 0));
}
}
if (!empty($images)) {
foreach ($images as $key => $value) {
$image_name = $this->Gallery->get_imagesG(NULL, array('id' => $value))->row()->name;
unlink($this->path . '/' . $listId . '/' . $image_name);
$conditions = array("id" => $value);
$this->Common_model->deleteTableData('list_photo', $conditions);
}
}
if (isset($_FILES["userfile"]["name"])) {
$insertData['list_id'] = $listId;
if (!is_dir($this->path . '/' . $listId)) {
//echo $this->path.'/'.$id;
mkdir($this->path . '/' . $listId, 0777, true);
$insertData['is_featured'] = 1;
}
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->path . '/' . $listId,
'encrypt_name' => TRUE,
'remove_spaces' => TRUE
);
//echo $this->path.'/'.$id;
$this->load->library('upload', $config);
$data = $this->upload->do_upload();
if ($data) {
$this->outputData['file'] = $this->upload->data();
$insertData['name'] = $this->outputData['file']['file_name'];
$insertData['created'] = local_to_gmt();
if ($this->outputData['file']['file_name'] != '')
$this->Common_model->insertData('list_photo', $insertData);
}
}
}
There's nothing in the lower piece of code to generate the thumb file.
You need something like this:
$this->thumb_path = realpath(APPPATH . '../directory/in/codeigniter/site/image/thumb');
Then after you have done the image upload in $this->upload->data() you will need to generate the thumb (adjust for your settings)
$thumb_config = array(
'source_image' => $data['full_path'],
'new_image' => $this->thumb_path,
'maintain_ratio' => true,
'width' => 200,
'height' => 200,
'quality' => '100%'
);
$this->load->library('image_lib', $thumb_config);
$this->image_lib->resize();
generate images thumb you need to use Image Processing (ImageMagick)
i provide below code to generate image thumbs.
function GenerateThumbnails($sourcePath1 = NULL, $destinationPath1 = NULL, $fileNames = NULL, $width = NULL, $height = NULL) {
try {
$sourcePath = $sourcePath1;
$destinationPath = $sourcePath . $destinationPath1 . "/";
if (isset($_POST['sourcePath'])) {
//$sourcePath = $_SERVER["DOCUMENT_ROOT"] . $_POST['sourcePath'];
$sourcePath = $_POST['sourcePath'];
}
if (isset($_POST['destinationPath'])) {
//$destinationPath = $_SERVER["DOCUMENT_ROOT"] . $_POST['destinationPath'];
$destinationPath = $_POST['destinationPath'];
}
if (isset($_POST['fileNames'])) {
$fileNames = json_decode($_POST['fileNames']);
}
if (isset($_POST['width'])) {
$width = $_POST['width'];
}
if (isset($_POST['height'])) {
$height = $_POST['height'];
}
foreach ($fileNames as $fileName) {
if (is_dir($sourcePath)) {
if (file_exists($sourcePath . $fileName)) {
$fetchFileExtension = array_values(array_filter(explode(".", $fileName)));
$fileExtension = end($fetchFileExtension);
$sourcePathFileName = $sourcePath . $fileName;
$destinationPathFileName = $destinationPath . $fileName;
$image = new Imagick();
$image->readImage($sourcePathFileName);
$image->scaleImage(1000, 0);
$image->setImageColorspace(255);
$image->setImageFormat('jpg');
$image = $image->flattenImages();
$image->thumbnailImage($width, $height, true);
(is_dir($destinationPath)) ? $image->writeImage($destinationPathFileName) : (createDirectory($destinationPath) AND $image->writeImage($destinationPathFileName));
chmod($destinationPathFileName, 0777);
$image->clear();
$image->destroy();
list($width1, $height1) = getimagesize($destinationPathFileName);
$data['orientation'] = ($width1 > $height1) ? 1 : 2;
$data['thumbnailChecksum'] = md5_file($destinationPathFileName);
$data['message'] = "Thumbnail created successfully .";
} else {
$data['message'] = "Thumbnail creation failed.";
}
}
}
return $data;
} catch (Exception $ex) {
print $ex->getMessage();
return false;
}
}