Create thumb after upload/ PHP Codeigneter - php

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;
}
}

Related

trim() expects parameter 1 to be string

Got a situation with image import process, before asking here of course - tried many ways to solve it by myself, but without any luck yet.
I'm getting error in model file: trim() expects parameter 1 to be string, array given in file /.../file.php on line 3875. Have to mention that - when there's single image - importing that perfectly, as soon as getting multiple images (more than one) - getting this error, and doesn't importing any image, just skipping.
Line 387: $image = trim($image);
Whole function code:
protected function imageHandler($field, &$config, $multiple = false, $item_id = NULL) {
$image_array = array();
if (empty($config['columns'][$field])) {
if ($multiple) {
return $image_array;
} else {
return '';
}
}
$sort_order = 0;
foreach ((array) $config['columns'][$field] as $images) {
if (!empty($config['multiple_separator']) && is_string($images)) {
$images = explode(#html_entity_decode($config['multiple_separator']), $images);
}
//is_array($images) && reset($images);
if ($multiple && is_array($images) && $config['columns']['image'] == $images[key($images)]) {
array_shift($images);
}
foreach ((array) $images as $image) {
$image = trim($image);
if ($config['image_download'] && $image) {
// if (substr($image, 0, 2) == '//') {
// $image = 'http:' . $image;
// }
$file_info = pathinfo(parse_url(trim($image), PHP_URL_PATH));
// if no extension, get it by mime
if (empty($file_info['extension'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($image));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
switch($contentType) {
case 'image/bmp': $file_info['extension'] = 'bmp'; break;
case 'image/gif': $file_info['extension'] = 'gif'; break;
case 'image/jpeg': $file_info['extension'] = 'jpg'; break;
case 'image/pipeg': $file_info['extension'] = 'jfif'; break;
case 'image/tiff': $file_info['extension'] = 'tif'; break;
case 'image/png': $file_info['extension'] = 'png'; break;
default: $file_info['extension'] = '';
}
}
if (substr_count($file_info['dirname'], 'http')) {
// incorrect array extract
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $this->language->get('warning_incorrect_image_format') . ' ' . str_replace(' ', '%20', $image),
);
if (!$multiple) {
return $image;
} else {
$image_array[] = $image;
continue;
}
}
if ($this->simulation) {
if (!$multiple) {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
return array('error_format', $image);
}*/
return $image;
} else {
/* Now handled before
if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
$image_array[] = 'error_format';
continue;
}*/
$image_array[] = $image;
continue;
}
}
// detect if image is on actual server
if (strpos($image, 'http') === false) {
$filename = trim($image);
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
continue;
}
}
if (version_compare(VERSION, '2', '>=')) {
$path = 'catalog/';
//$http_path = HTTP_CATALOG . 'image/catalog/';
} else {
$path = 'data/';
//$http_path = HTTP_CATALOG . 'image/data/';
}
if (trim($config['image_location'], '/\\')) {
$path .= trim($config['image_location'], '/\\') . '/';
}
if ($config['image_keep_path'] && trim($file_info['dirname'], '/\\')) {
$path .= trim($file_info['dirname'], '/\\') . '/';
}
if (!is_dir(DIR_IMAGE . $path)) {
mkdir(DIR_IMAGE . $path, 0777, true);
}
$filename = $path . urldecode($file_info['filename']) . '.' . $file_info['extension'];
if (($item_id === false && $this->config->get('mlseo_insertautoimgname')) || ($item_id && $this->config->get('mlseo_editautoimgname'))) {
$this->load->model('tool/seo_package');
$seo_image_name = $this->model_tool_seo_package->transformProduct($this->config->get('mlseo_product_image_name_pattern'), $this->config->get('config_language_id'), $config['columns']);
$seoPath = pathinfo($filename);
if (!empty($seoPath['filename'])) {
$seoFilename = $this->model_tool_seo_package->filter_seo($seo_image_name, 'image', '', '');
$filename = $seoPath['dirname'] . '/' . $seoFilename . '.' . $seoPath['extension'];
if (file_exists(DIR_IMAGE . $filename)) {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $seoPath['dirname'] . '/' . $seoFilename . '-' . $x . '.' . $seoPath['extension'];
$x++;
}
}
}
}
if ($config['image_exists'] == 'rename') {
$x = 1;
while (file_exists(DIR_IMAGE . $filename)) {
$filename = $path . urldecode($file_info['filename']) . '-' . $x++ . '.' . $file_info['extension'];
}
} else if ($config['image_exists'] == 'keep' && file_exists(DIR_IMAGE . $filename)) {
// image skipped
if (!$multiple) {
return $filename;
} else {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
continue;
}
}
// copy image, replace space chars for compatibility with copy()
// if (!#copy(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename)) {
$copyError = $this->copy_image(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename);
if ($copyError !== true) {
if (defined('GKD_CRON')) {
$this->cron_log($this->session->data['obui_current_line'] . ' - ' . $copyError);
} else {
$this->session->data['obui_log'][] = array(
'row' => $this->session->data['obui_current_line'],
'status' => 'error',
'title' => $this->language->get('warning'),
'msg' => $copyError,
);
}
$filename = '';
}
} else {
// get direct value
$filename = trim($image);
if ($this->simulation) {
if (!$multiple) {
return $filename;
} else {
if (!empty($filename)) {
$image_array[] = $filename;
}
continue;
}
}
}
// one field only, directly return first value
if (!$multiple) {
return $filename;
}
if (!empty($filename)) {
$image_array[] = array(
'image' => $filename,
'sort_order' => $sort_order++,
);
}
}
}
return $image_array;
}
Tried to use return $image; after that line, even that didn't helped. Was trying to find similar problem to this one to find a solution without posting here, but seems like I won't move anywhere withou help. Thanks in advance!

Only first image uploaded, Upload multiple images individually in Laravel

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;
}

How to Replace and Delete previous files uploaded, when Edit a record in Laravel 4.2

I use laravel 4.2, because this project has been around for years. :)
Now, how can i replace and delete previous files uploaded in public
directory, when edit a record ?
Given the following Controller code ( Update Methode ) :
public function update($id)
{
$idd = Sentry::getUser()->id;
try {
$validator = Validator::make(
Input::all(),
array(
'first_name' => 'required',
'last_name' => 'required',
'eng_certificate' => 'image|mimes:png,jpeg,jpg|max:1100',
'profile_img' => 'image|mimes:png,jpeg,jpg|max:1100',
)
);
if ($validator->passes()) {
$profile = User::find($id);
$profile->first_name = Input::get('first_name');
$profile->last_name = Input::get('last_name');
if (Evidence::where('user_id', $idd)->count() == 0) {
$evidence = new Evidence;
$evidence->user_id = $idd;
$evidence->created_at = jDate::forge()->time();
} else {
$evidence = Evidence::where('user_id', $idd)->first();
$evidence->updated_at = jDate::forge()->time();
}
if (Input::hasFile('eng_certificate')) {
$image = Input::file('eng_certificate');
$destinationPath = 'uploads/evidence';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->eng_certificate = $image_filename;
$evidence->save();
}
}
if (Input::hasFile('profile_img')) {
$image = Input::file('profile_img');
$destinationPath = 'uploads/evidence/profile_img/';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->profile_img = $image_filename;
$evidence->save();
}
}
$profile->save();
return Redirect::route('cpanel.home')->with('success', 'اطلاعات پروفایل شما با موفقیت بروز گردید.');
}
else {
return Redirect::back()->withInput()->withErrors($validator->messages());
}
}
catch (LoginRequiredException $e) {
return Redirect::back()->withInput()->with('danger', $e->getMessage());
}
}
How can I fix it?
Thank you.
find out current file location
use php unlink function
https://www.w3schools.com/php/func_filesystem_unlink.asp
You can interact with the filesystem by using: Laravel Filesystem
For example:
Storage::delete('file.jpg');
See: https://laravel.com/docs/5.8/filesystem#deleting-files

Image upload script - how to resize

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`;

Opencart product import image is not working

Hy all,
I'm working on an import of more than 30.000 products from an old webshop system to my OpenCart application.
I've got the categories working, and the products, but there is only 1 thing that i can't fix. That is that there's no image.
I've uploaded all images in OpenCartRoot/image/data/old/tt_productsv2/images/
In the database, it is inserted:
image/old/tt_productsv2/images/greatest.jpg
I've confirmed that that image exist, but when i check the front-end page, there are no images. Also when i check the back-end, i don't see any image linked to the product.
So my question is, what wrong I have done? Why isn't the image linked to the product, although i inserted the link in the database...
The path to the image in the database should only be
old/tt_productsv2/images/greatest.jpg
as OpenCart will build the path like
DIR_IMAGE . 'old/tt_productsv2/images/greatest.jpg'
where DIR_IMAGE is defined like
define('DIR_IMAGE', '/path/to/web/root/image/');
Yes, this is a problem with GLOBAL_BRACE Constant.
Some servers do not support that constant value, so you can change the
server or change the code.
The code is in:
admin / controller / common/ filemanager.php
line No : 37 ===================================================================
<?php
class ControllerCommonFileManager extends Controller {
public function index() {
$this->load->language('common/filemanager');
if (isset($this->request->get['filter_name'])) {
$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['images'] = array();
$this->load->model('tool/image');
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
// $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
$files1 = glob($directory . '/' . $filter_name . '*.jpg');
if (!$files1) {
$files1 = array();
}
$files2 = glob($directory . '/' . $filter_name . '*.jpeg');
if (!$files2) {
$files2 = array();
}
$files3 = glob($directory . '/' . $filter_name . '*.JPG');
if (!$files3) {
$files3 = array();
}
$files4 = glob($directory . '/' . $filter_name . '*.png');
if (!$files4) {
$files4 = array();
}
$files5 = glob($directory . '/' . $filter_name . '*.JPEG');
if (!$files5) {
$files5 = array();
}
$files6 = glob($directory . '/' . $filter_name . '*.PNG');
if (!$files6) {
$files6 = array();
}
$files7 = glob($directory . '/' . $filter_name . '*.GIF');
if (!$files7) {
$files7 = array();
}
$files8 = glob($directory . '/' . $filter_name . '*.gif');
if (!$files8) {
$files8 = array();
}
$files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8);
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true)
);
} elseif (is_file($image)) {
// Find which protocol to use to pass the full image link back
if ($this->request->server['HTTPS']) {
$server = HTTPS_CATALOG;
} else {
$server = HTTP_CATALOG;
}
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
);
}
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['entry_search'] = $this->language->get('entry_search');
$data['entry_folder'] = $this->language->get('entry_folder');
$data['button_parent'] = $this->language->get('button_parent');
$data['button_refresh'] = $this->language->get('button_refresh');
$data['button_upload'] = $this->language->get('button_upload');
$data['button_folder'] = $this->language->get('button_folder');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_search'] = $this->language->get('button_search');
$data['token'] = $this->session->data['token'];
if (isset($this->request->get['directory'])) {
$data['directory'] = urlencode($this->request->get['directory']);
} else {
$data['directory'] = '';
}
if (isset($this->request->get['filter_name'])) {
$data['filter_name'] = $this->request->get['filter_name'];
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($this->request->get['target'])) {
$data['target'] = $this->request->get['target'];
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($this->request->get['thumb'])) {
$data['thumb'] = $this->request->get['thumb'];
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($this->request->get['directory'])) {
$pos = strrpos($this->request->get['directory'], '/');
if ($pos) {
$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
}
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
// Refresh
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode($this->request->get['directory']);
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_name'])) {
$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$pagination = new Pagination();
$pagination->total = $image_total;
$pagination->page = $page;
$pagination->limit = 16;
$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);
$data['pagination'] = $pagination->render();
$this->response->setOutput($this->load->view('common/filemanager', $data));
}
public function upload() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array(
'jpg',
'jpeg',
'gif',
'png'
);
if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif'
);
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);
$json['success'] = $this->language->get('text_uploaded');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function folder() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->language->get('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->language->get('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
chmod($directory . '/' . $folder, 0777);
$json['success'] = $this->language->get('text_directory');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function delete() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
if (isset($this->request->post['path'])) {
$paths = $this->request->post['path'];
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == DIR_IMAGE . 'catalog') {
$json['error'] = $this->language->get('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->language->get('text_delete');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}

Categories