protected function beforeSave() { if (!parent::beforeSave()) { return false; } if (($this->scenario == 'insert' || $this->scenario == 'update') && ($this->icon = CUploadedFile::getInstance($this, 'icon'))) { // Если обновляем запись, то удаляем прошлую фотографию if ($this->scenario == 'update') { $file = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/Stock/' . $this->img; $fileMini = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/Stock/mini-' . $this->img; if (file_exists($file) and $this->img != '') { unlink($file); } if (file_exists($fileMini) and $this->img != '') { unlink($fileMini); } } $fileName = mktime(date("i")) . '.jpg'; $this->img = $fileName; $file = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/Stock/' . $fileName; $this->icon->saveAs($file); //Делаем ресайз только что загруженному изображению $Image = Image::factory("./Image/Stock/" . $fileName); if ($Image->width >= $Image->height) { $Image->resize(375, 410, Image::WIDTH)->crop(375, 410, "top", "center"); $Image->save($_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/Stock/mini-' . $fileName); } else { $Image->resize(235, 314, Image::HEIGHT)->crop(235, 314, "top", "center"); $Image->save($_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/Stock/mini-' . $fileName); } } return true; }
/** * Creates a new instance for static use of the class. * * @return Image_Driver */ protected static function instance() { if (Image::$_instance == null) { Image::$_instance = Image::factory(); } return Image::$_instance; }
/** * Crop the input image so that it matches the aspect ratio specified in the * rectangle_thumbs.aspect_ratio module setting. Focus on the center of the image and crop out * the biggest piece that we can. * * @param string $input_file * @param string $output_file * @param array $options */ static function crop_to_aspect_ratio($input_file, $output_file, $options) { graphics::init_toolkit(); if (@filesize($input_file) == 0) { throw new Exception("@todo EMPTY_INPUT_FILE"); } list($desired_width, $desired_height) = explode(":", module::get_var("rectangle_thumbs", "aspect_ratio")); $desired_ratio = $desired_width / $desired_height; // Crop the largest rectangular section we can out of the original image. Start with a // rectangular section that's guaranteed to be too large, then shrink it horizontally to just // barely fit. If it's still too tall vertically, shrink both dimensions proportionally until // the horizontal edge fits as well. $dims = getimagesize($input_file); if ($desired_ratio == 1) { $new_width = $new_height = min($dims[0], $dims[1]); } else { if ($desired_ratio < 1) { list($new_width, $new_height) = array($dims[0], $dims[0] / $desired_ratio); } else { list($new_width, $new_height) = array($dims[1] * $desired_ratio, $dims[1]); } } if ($new_width > $dims[0]) { // Too wide, scale it down list($new_width, $new_height) = array($dims[0], $dims[0] / $desired_ratio); } if ($new_height > $dims[1]) { // Too tall, scale it down some more $new_width = min($dims[0], $dims[1] * $desired_ratio); $new_height = $new_width / $desired_ratio; } $new_width = round($new_width); $new_height = round($new_height); Image::factory($input_file)->crop($new_width, $new_height)->quality(module::get_var("gallery", "image_quality"))->save($output_file); }
function index() { if (!empty($_GET['img']) and !empty($_GET['h']) and !empty($_GET['w'])) { $img = Image::factory('media/images/' . $_GET['img'])->resize($_GET['w'], $_GET['h'], Image::NONE)->render('jpg', 60); return $img; } }
/** * Rotate an image. Valid options are degrees * * @param string $input_file * @param string $output_file * @param array $options */ static function rotate($input_file, $output_file, $options) { graphics::init_toolkit(); module::event("graphics_rotate", $input_file, $output_file, $options); // BEGIN mod to original function $image_info = getimagesize($input_file); // [0]=w, [1]=h, [2]=type (1=GIF, 2=JPG, 3=PNG) if (module::get_var("image_optimizer", "rotate_jpg") || $image_info[2] == 2) { // rotate_jpg enabled, the file is a jpg. get args $path = module::get_var("image_optimizer", "path_jpg"); $exec_args = " -rotate "; $exec_args .= $options["degrees"] > 0 ? $options["degrees"] : $options["degrees"] + 360; $exec_args .= " -copy all -optimize -outfile "; // run it - from input_file to tmp_file $tmp_file = image_optimizer::make_temp_name($output_file); exec(escapeshellcmd($path) . $exec_args . escapeshellarg($tmp_file) . " " . escapeshellarg($input_file), $exec_output, $exec_status); if ($exec_status || !filesize($tmp_file)) { // either a blank/nonexistant file or an error - log an error and pass to normal function Kohana_Log::add("error", "image_optimizer rotation failed on " . $output_file); unlink($tmp_file); } else { // worked - move temp to output rename($tmp_file, $output_file); $status = true; } } if (!$status) { // we got here if we weren't supposed to use jpegtran or if jpegtran failed // END mod to original function Image::factory($input_file)->quality(module::get_var("gallery", "image_quality"))->rotate($options["degrees"])->save($output_file); // BEGIN mod to original function } // END mod to original function module::event("graphics_rotate_completed", $input_file, $output_file, $options); }
public function _upload_image(Validate $array, $input) { if ($array->errors()) { // Don't bother uploading return; } // Get the image from the array $image = $array[$input]; if (!Upload::valid($image) or !Upload::not_empty($image)) { // No need to do anything right now return; } if (Upload::valid($image) and Upload::type($image, $this->types)) { $filename = strtolower(Text::random('alnum', 20)) . '.jpg'; if ($file = Upload::save($image, NULL, $this->directory)) { Image::factory($file)->resize($this->width, $this->height, $this->resize)->save($this->directory . $filename); // Update the image filename $array[$input] = $filename; // Delete the temporary file unlink($file); } else { $array->error('image', 'failed'); } } else { $array->error('image', 'valid'); } }
private function cache() { // is it a remote image? if ($this->is_remote()) { $path = $this->image_folder . '/imagecache/original'; $image_original_name = "{$path}/" . preg_replace('/\\W/i', '-', $this->image_src); if (!file_exists($image_original_name)) { //make sure the directory(s) exist System::mkdir($path); // download image copy($this->image_src, $image_original_name); } unset($path); } else { // $image_original_name = Route::get('media')->uri(array('file' => $this->image_src)); $image_original_name = Kohana::find_file('media', $this->image_src, FALSE); } //if image file not found stop here if (!$this->is_valid($image_original_name)) { return FALSE; } $this->resized_image = "{$this->image_folder}/imagecache/{$this->resize_type}/{$this->width}x{$this->height}/{$this->image_src}"; if (!file_exists($this->resized_image)) { //make sure the directory(s) exist $path = pathinfo($this->resized_image, PATHINFO_DIRNAME); System::mkdir($path); // Save the resized image to the public directory for future requests $image_function = $this->resize_type === 'crop' ? 'crop' : 'resize'; Image::factory($image_original_name)->{$image_function}($this->width, $this->height)->save($this->resized_image, 85); } return TRUE; }
public function action_index() { //путь до картинки $src = 'img/user/kottedzh-russkiy-dar_e26ce03e3c12ea32a84.JPG'; $image = Image::factory(getcwd() . DIRECTORY_SEPARATOR . $src); $image->resize(800, 600); }
public function action_preview2() { $dir = $this->uploads_dir(); // build image file name $filename = $this->request->param('filename'); // check if file exists if (!file_exists($filename) or !is_file($filename)) { throw new HTTP_Exception_404('Picture not found'); } $cachenamearr = explode('/', $filename); $name = array_pop($cachenamearr); $cachename = 'a2' . $name; $cachename = str_replace($name, $cachename, $filename); /** @var Image $image **/ // trying get picture preview from cache if (($image = Cache::instance()->get($cachename)) === NULL) { // create new picture preview $image = Image::factory($filename)->resize(null, 50)->crop(50, 50)->render(NULL, 90); // store picture in cache Cache::instance()->set($cachename, $image, Date::MONTH); } // gets image type $info = getimagesize($filename); $mime = image_type_to_mime_type($info[2]); // display image $this->response->headers('Content-type', $mime); $this->response->body($image); }
public function action_save($pid = null) { $data = (object) filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); $photo = ORM::factory("dlsliderphoto", $pid); $slider = ORM::factory("dlslidergroup", $data->slider_id); $new = empty($photo->id); if (!$slider->loaded()) { Message::set(Message::ERROR, "Something unexpected happened. Please try again."); $this->request->redirect("admin/dlslider/"); return; } $files = Validate::factory($_FILES); $files->rule('photo', 'Upload::type', array(array('jpg', 'png', 'gif'))); foreach ($data as $val) { if (empty($val)) { Message::set(Message::ERROR, "All fields must be filled in."); $this->request->redirect("admin/dlslider/edit/{$slider->id}"); return; } } $photo->title = $data->title; $photo->teaser = $data->teaser; $photo->link_text = $data->linktext; $photo->link = $data->link; $photo->saved = isset($data->save) ? 1 : 0; if (empty($photo->position)) { $photo->position = $slider->allPhotos->count() + 1; } if ($files->check()) { if ($_FILES['photo']['error'] == 0) { $filename = upload::save($_FILES['photo'], $_FILES['photo']['name'], Kohana::config('myshot.relativeBase')); // New file name $new_filename = rand(0, 1000) . "_" . substr($_FILES['photo']['name'], 0, strlen($_FILES['photo']['name']) - 4) . '-resized' . substr($_FILES['photo']['name'], -4); $localFile = Kohana::config('myshot.relativeBase') . $new_filename; // Resize, sharpen, and save the image Image::factory($filename)->resize(Model_DLSliderPhoto::WIDTH, Model_DLSliderPhoto::HEIGHT, Image::WIDTH)->crop(Model_DLSliderPhoto::WIDTH, Model_DLSliderPhoto::HEIGHT, 0, 0)->save($localFile); Library_Akamai::factory()->addToDir($localFile, "dlslider", date("Y-m")); $photo->filename = "dlslider/" . date("Y-m") . "/{$new_filename}"; // Remove the temporary files unlink($filename); unlink($localFile); } } if (empty($photo->filename)) { Message::set(Message::ERROR, "Something was wrong with the file to upload. Please check the file try again."); $this->request->redirect("admin/dlslider/edit/{$slider->id}"); return; } $photo->save(); if ($new) { DB::update("dl_slider_group_dl_slider_photos")->set(array("position" => $slider->allPhotos->count()))->where("dl_slider_group_id", "=", $slider->id)->where("dl_slider_photos_id", "=", $photo->id)->execute(); } !$slider->has("photos", $photo) ? $slider->add("photos", $photo) : null; Message::set(Message::SUCCESS, "Image Added"); $this->request->redirect("admin/dlslider/edit/{$slider->id}"); }
/** * Crop the input image so that it's square. Focus on the center of the image. * * @param string $input_file * @param string $output_file * @param array $options */ static function crop_to_square($input_file, $output_file, $options) { graphics::init_toolkit(); if (@filesize($input_file) == 0) { throw new Exception("@todo EMPTY_INPUT_FILE"); } $size = module::get_var("gallery", "thumb_size"); $dims = getimagesize($input_file); Image::factory($input_file)->crop(min($dims[0], $dims[1]), min($dims[0], $dims[1]))->quality(module::get_var("gallery", "image_quality"))->save($output_file); }
/** * Image nudity detector based on flesh color quantity. * * @param array $file uploaded file data * @param string $threshold Threshold of flesh color in image to consider in pornographic. See page 302 * @return boolean */ public static function not_nude_image(array $file, $threshold = 0.5) { if (Upload::not_empty($file)) { $image = Image::factory($file['tmp_name']); if ($image->is_nude_image($threshold)) { return FALSE; } } return TRUE; }
public static function save_uploaded_image($image, $target_path) { if (Model_Image::validate_uploaded_image($image)) { if ($file = Upload::save($image, NULL, DOCROOT . "images/")) { Image::factory($file)->save($target_path); // Delete the temporary file unlink($file); return TRUE; } } return FALSE; }
public function action_get_image() { $this->auto_render = FALSE; if (Arr::get($_SERVER, 'HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest') { $image = ORM::factory('image', Arr::get($_POST, 'id')); $image = Arr::merge($image->as_array(), Arr::extract((array) Image::factory('images/' . $image->id . '/original' . $image->ext), array('width', 'height'))); $this->response->headers('Content-Type: application/json; charset=utf-8'); $this->response->body(json_encode($image)); } else { $this->response->body('Only AJAX request'); } }
public static function exact($filename, $width, $height) { $img = Image::factory($filename)->resize($width, $height, Image::INVERSE)->crop($width, $height); $nameparts = explode('/', $filename); $fname = end($nameparts); $path = implode('/', array_slice($nameparts, 0, count($nameparts) - 1)) . '/'; $filenameparts = explode('.', $fname); $newname = implode('.', array_slice($filenameparts, 0, count($filenameparts) - 1)) . $width . 'x' . $height . '.' . self::imgtype_to_ext($img->type); $img->save($path . $newname); $img->file = $newname; return $img; }
public function save_cover($cover) { $new_name = bin2hex(openssl_random_pseudo_bytes(5)); $cover['name'] = $new_name . '.' . pathinfo($cover['name'], PATHINFO_EXTENSION); $uploaddir = 'upload/covers/'; if ($file = Upload::save($cover, NULL, $uploaddir)) { Image::factory($file)->save($uploaddir . $cover['name']); unlink($file); return $cover['name']; } else { return false; } }
public function resizeHonor($path, $height) { $img = Image::factory($path); $path_info = pathinfo($path); $savedAt = $path_info['dirname'] . '/' . $path_info['filename'] . '_x' . $height . '.' . $path_info['extension']; if ($img->height > $height) { $img->resize(NULL, $height, Image::HEIGHT); } if ($img->save($savedAt)) { Library_Akamai::factory()->addToDir($savedAt, Kohana::config('akamai.honordir')); return $savedAt; } }
protected function _process_file() { $image = $_FILES[$this->name()]; if ($file = Upload::save($image, NULL, DOCROOT . $this->_upload_dir)) { $filename = strtolower(Text::random('alnum', 20)) . '.jpg'; Image::factory($file)->save(DOCROOT . $this->_upload_dir . $filename); // Delete the temporary file unlink($file); $this->_uploaded = true; $this->_file_address = $this->_upload_dir . $filename; return true; } return false; }
private function __upload_logo() { $_FILES = Validation::factory($_FILES)->add_rules('file', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[2M]'); unlink(DOCROOT . 'zest/images/logo.jpg'); // Temporary file name $filename = upload::save('file'); // Resize, sharpen, and save the image $img = Image::factory($filename); $img->resize(150, 80, Image::AUTO); $img->save(DOCROOT . 'zest/images/logo.jpg'); // Remove the temporary file unlink($filename); $this->__throw_success("The image has been successfully uploaded!"); $this->__throw_warning("If the logo appears to be unchanged, the logo will change next time you login."); return true; }
protected function _save_img_bg($image) { if (!upload::valid($image) or !upload::type($image, array('jpg', 'jpeg', 'png', 'gif'))) { $this->session->set_flash('error_msg', 'Only upload file jpg , jpeg , png , gif'); url::redirect('admin_config'); } else { $directory = DOCROOT . 'themes/client/styleSIC/index/pics/'; if ($file = upload::save($image, NULL, $directory)) { $filename = 'bg_' . md5(rand(0, 999)) . time() . '.png'; Image::factory($file)->save($directory . $filename); // Delete the temporary file unlink($file); return $filename; } return FALSE; } }
/** * Загрузка имаги * @param $company_id * @param $user_id */ private function _upload($company_id, $user) { $validation = Validation::factory($_FILES)->rule('files', 'not_empty'); if ($validation->check()) { $file = (object) array('type' => $validation['files']['type'][0], 'tmp_name' => $validation['files']['tmp_name'][0], 'size' => $validation['files']['size'][0], 'name' => $validation['files']['name'][0], 'error' => $validation['files']['error']); $company = ORM::factory('service', $company_id); $settings = (object) Kohana::$config->load('gallery'); /** * Если файл есть * И папка доступна для записи * И такая компания есть * И ты админ или хозяин компании */ if ($file->size > 0 and is_writable($settings->img_path) and $company->loaded() and ($user->has('roles', 2) or $company->user_id == $user->id)) { // Манипуляция с временным изображением $image = Image::factory($file->tmp_name); // Название изображения $file_name = $company->id . '_' . md5(Date::formatted_time() . $file->name) . '.' . File::ext_by_mime($file->type); if ($image->width > $settings['img_max_width']) { $image->resize($settings['img_max_width'], NULL); } $image->save($settings['img_path'] . $file_name); if ($image->height > $settings['thumb_img_max_width']) { $image->resize(NULL, $settings['thumb_img_max_width']); } $image->save($settings['img_path'] . $settings['thumb_file_name_prefix'] . $file_name); unlink($file->tmp_name); $company_image = ORM::factory('CompanyImage'); $company_image->name = $file->name; $company_image->date_created = Date::formatted_time(); $company_image->img_path = $settings['img_path'] . $file_name; $company_image->thumb_img_path = $settings['img_path'] . $settings['thumb_file_name_prefix'] . $file_name; $company_image->company_id = $company->id; $company_image->title = trim(Arr::path($_POST, 'title')) ? Arr::path($_POST, 'title') : $company_image->name; $company_image->save(); $company->date_edited = Date::formatted_time(); $company->update(); $this->data[] = (object) array('title' => $company_image->title, 'url' => '/' . $company_image->img_path, 'thumbnail_url' => '/' . $company_image->thumb_img_path, 'delete_url' => '/rest/companyimage/index/' . $company_image->id . '?company_id=' . $company->id, 'delete_type' => 'DELETE', 'image_id' => $company_image->id, 'company_id' => $company_image->company->id); $redirect = $this->request->post('redirect') ? stripslashes($this->request->post('redirect')) : null; // Редирект для IE if ($redirect) { $this->request->redirect(sprintf($redirect, rawurlencode(json_encode($this->data)))); } } } }
protected function beforeSave() { if (!parent::beforeSave()) { return false; } if ($this->scenario == 'insert' && isset($this->icon)) { $fileName = mktime(date("i")) . rand(1, 100) . rand(1, 100) . '.jpg'; $this->img = $fileName; $file = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/AttachmentProject/' . $fileName; $this->icon->saveAs($file); //Делаем ресайз только что загруженному изображению $Image = Image::factory("./Image/AttachmentProject/" . $fileName); $Image->resize(375, 210, Image::WIDTH); $Image->save($_SERVER['DOCUMENT_ROOT'] . Yii::app()->getBaseUrl() . '/Image/AttachmentProject/mini-' . $fileName); } return true; }
public function gallery_remove_image($id) { if (!$this->loginmanager->is_logged_in()) { die(json_encode(array('message' => 'You are not logged in!', 'status' => 'Error!'))); } $im = GalleryItem::factory((int) $id); $content = $im->content->get(); if (!$this->user->can_edit_content($content)) { die(json_encode(array('message' => 'You are not allowed to manage images in this gallery!', 'status' => 'Error!'))); } $img = Image::factory($im->filename); $img->remove_thumbnails(); @unlink($im->filename); $im->delete(); $content->updated = time(); $content->save(); die(json_encode(array('message' => 'Image is successfully removed.', 'status' => 'OK'))); }
/** * осуществляет проверку загружаемого изображения на jpg(jpeg) * копирует его в католог img, предварительно * изменив размер до s - max(300*300) m - max(800*800) схранив пропорции * @param $file string полное имя файла * @return mixed new file name or false(boolean) */ public function load($file, $id = '') { if (!Upload::valid($file) || !Upload::not_empty($file) || !Upload::type($file, array('jpg', 'jpeg'))) { return false; } $dir = DOCROOT . self::IMAGE_DIR; if ($image = Upload::save($file, NULL, $dir)) { if ($id == '') { $id = Text::random('alnum', 32); } $name = $id . '.jpg'; Image::factory($image)->resize(300, 300, Image::AUTO)->save($dir . 's_' . $name); Image::factory($image)->resize(800, 800, Image::AUTO)->save($dir . 'm_' . $name); unlink($image); return $name; } return false; }
/** * Add image to item * @return void * @param integer id of item * @param string dir with images */ public function add_image($item, $dir) { // Check for user permission if (user::is_got()) { $this->set_title(Kohana::lang('gallery.add_image')); $this->add_breadcrumb(Kohana::lang('gallery.add_image'), url::current()); // Set redirect URL if (isset($_POST['redirect'])) { $redirect = $_POST['redirect']; } else { $redirect = request::referrer(); } $form = array('image' => '', 'redirect' => $redirect); $errors = array(); if (isset($_FILES)) { $files = new Validation($_FILES); // Rules $files->add_rules('image', 'upload::valid', 'upload::required', 'upload::type[jpg,jpeg]', 'upload::size[500K]'); if ($files->validate()) { // Temporary file $filename = upload::save('image'); // Get new name $id = gallery::get_image_new_name($item, $dir); // Save original and thumb Image::factory($filename)->save('./data/' . $dir . '/' . $item . '_' . $id . '.jpg'); Image::factory($filename)->resize(128, 128, Image::AUTO)->quality(85)->save('./data/' . $dir . '/' . $item . '_' . $id . '_m.jpg'); // Remove the temporary file unlink($filename); url::redirect($form['redirect']); } else { // Repopulate form with error and original values $form = arr::overwrite($form, $files->as_array()); $errors = $files->errors('gallery_errors'); } } // View $this->template->content = new View('admin/add_image'); $this->template->content->errors = $errors; $this->template->content->form = $form; } else { url::redirect('/denied'); } }
public function _upload_img($file, $ext = NULL, $directory = NULL) { if ($directory == NULL) { $directory = 'media/uploads'; } if ($ext == NULL) { $ext = 'jpg'; } $symbols = '3x45346p513a2gzeg4369789fsgtrgzfsdfsdvcnvma'; $filename = substr(str_shuffle($symbols), 0, 16); $im = Image::factory($file); if ($im->width > 150) { $im->resize(150); } $im->save("{$directory}/small_{$filename}.{$ext}"); $im = Image::factory($file); $im->save("{$directory}/{$filename}.{$ext}"); return "{$filename}.{$ext}"; }
/** * Upload an image and return the filename. * Will change the post field to the URL of the image after saving. * @Developer brandon * @Date Apr 20, 2010 * @Param (string) $post_field * @Param (string) $directory * @Param (int) $width * @Param (int) $height * @Return (any) (either the filename that was saved, or false if couldn't save) */ public static function process($post_field = 'image', $directory = NULL, $width = 100, $height = 100) { $files = Validation::factory($_FILES)->add_rules($post_field, 'upload::valid', 'upload::required', 'upload::type[gif,jpg,png]'); if ($files->validate()) { // Temporary file name $filename = upload::save($post_field); $new_filename = preg_replace('/[^0-9a-zA-Z_.]/', '', basename($filename)); // Resize, sharpen, and save the image Image::factory($filename)->resize($width, $height, Image::WIDTH)->crop($width, $height)->save(Kohana::config('upload.directory') . $directory . $new_filename); // Remove the temporary file unlink($filename); // Set the post field $_POST[$post_field] = $new_filename; return $new_filename; } else { unset($_POST[$post_field]); return false; } }
public function action_image() { //get image $image = $_FILES['profile_image']; //file post if (!Upload::valid($image) or !Upload::not_empty($image) or !Upload::type($image, explode(',', core::config('image.allowed_formats'))) or !Upload::size($image, core::config('image.max_image_size') . 'M')) { if (Upload::not_empty($image) && !Upload::type($image, explode(',', core::config('image.allowed_formats')))) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not valid format, please use one of this formats "jpg, jpeg, png"')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } if (!Upload::size($image, core::config('image.max_image_size') . 'M')) { Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Is not of valid size. Size is limited on ' . core::config('general.max_image_size') . 'MB per image')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } Alert::set(Alert::ALERT, $image['name'] . ' ' . __('Image is not valid. Please try again.')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } else { if ($image != NULL) { $user_id = Auth::instance()->get_user()->id_user; // saving/uploadng zip file to dir. $root = DOCROOT . 'images/users/'; //root folder $image_name = $user_id . '.png'; $width = core::config('image.width'); // @TODO dynamic !? $height = core::config('image.height'); // @TODO dynamic !? $image_quality = core::config('image.quality'); // if folder doesnt exists if (!file_exists($root)) { mkdir($root, 775, true); } // save file to root folder, file, name, dir if ($file = Upload::save($image, $image_name, $root)) { // resize uploaded image Image::factory($file)->resize($width, $height, Image::AUTO)->save($root . $image_name, $image_quality); } Alert::set(Alert::SUCCESS, $image['name'] . ' ' . __('Image is uploaded.')); $this->request->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } } }
protected function _save_image($image, $directory) { if (!Upload::valid($image) || !Upload::not_empty($image) || !Upload::type($image, array('jpg', 'jpeg', 'png', 'gif')) || !Upload::size($image, '2M')) { return false; } if (!is_dir($directory)) { mkdir($directory, 0777, true); } if ($file = Upload::save($image, NULL, $directory)) { try { $filename = Text::random('alnum', 20) . '.jpg'; Image::factory($file)->save($directory . $filename); unlink($file); return $filename; } catch (ErrorException $e) { // ... } } return false; }
/** * Processes an uploaded image * * @return null */ public function action_upload() { // Validate the upload first $validate = new Validate($_FILES); $validate->rules('image', array('Upload::not_empty' => null, 'Upload::valid' => null, 'Upload::size' => array('4M'), 'Upload::type' => array(array('jpg', 'png', 'gif')))); if ($validate->check(true)) { // Shrink the image to the lowest max dimension $image = Image::factory($_FILES['image']['tmp_name']); $constraints = Kohana::config('image')->constraints; $image->resize($constraints['max_width'], $constraints['max_height']); $image->save(APPPATH . 'photos/' . $_FILES['image']['name']); $photo = new Model_Vendo_Photo(); $photo->file = APPPATH . 'photos/' . $_FILES['image']['name']; $photo->save(); unlink(APPPATH . 'photos/' . $_FILES['image']['name']); $this->request->redirect('admin/photo'); } else { Session::instance()->set('errors', $validate->errors('validate')); $this->request->redirect('admin/photo'); } }