public function doSaveMedia($v) { if ($v == null) { $image = $this->getImagePath(); if ($this->isNew) { $content = file_get_contents(sfConfig::get('sf_root_dir') . '/public_html' . $image); $size = getimagesize(sfConfig::get('sf_root_dir') . '/public_html' . $image); } else { return $this->getObject()->getImagesId(); } } else { $content = file_get_contents($v->getTempName()); $size = getimagesize($v->getTempName()); } $hash = md5($content); $criteria = new Criteria(); $criteria->add(ImagesPeer::CONTENT_HASH, $hash); $obj = ImagesPeer::doSelectOne($criteria); try { if (empty($obj)) { $obj = new Images(); $obj->setNameDownloadedFile($v->getOriginalName())->setNameFileForPage($v->getOriginalName())->setTypeImg($v->getType())->setHeight($size[2])->setWidth($size[1])->setContentHash($hash . '.jpg')->setContent(base64_encode($content))->setCreatedAt(date("Y-m-d H:i"))->setUpdatedAt(date("Y-m-d H:i"))->save(); } } catch (Exception $e) { echo "stdfdfdfdfrt"; die; } $criteria = new Criteria(); $criteria->add(ImagesPeer::CONTENT_HASH, $obj->getContentHash()); $obj = ImagesPeer::doSelectOne($criteria); return $obj->getId(); }
/** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $imagesModel = new Images(); $images = $imagesModel->getData($id); $userId = Albums::getAlbumAuthor($id); $this->render('view', array('model' => $this->loadModel($id), 'dataProvider' => $images, 'id' => $userId)); }
public function saveEdit(Images $img) { try { $db = $this->connectionToDataBase(); $sql = "UPDATE {$this->tabel} SET " . self::$Comment . " = ? WHERE imgName = ?"; $params = array($img->GetMSG(), $img->getImgName()); $query = $db->prepare($sql); $query->execute($params); } catch (Exception $e) { die('An unknown error hase happened'); } }
public function save() { $transaction = Yii::$app->db->beginTransaction(); try { $characteristics = new Characteristics(); $characteristics->display_type = $this->displayType; $characteristics->mechanism_type = $this->mechanismType; $characteristics->starp_type = $this->starpType; $characteristics->sex = $this->sex; if (!$characteristics->save(false)) { throw new \Exception('Charasteristic not save, transaction rollback'); } $products = new Products(); $products->clk_name = $this->name; $products->clk_description = $this->description; $products->characteristics_id = $characteristics->id; $products->price = $this->price; if (!$products->save(false)) { throw new \Exception('Product not save, transaction rollback'); } $hashName = Yii::$app->security->generateRandomString(); $fullImagePath = self::FULL_IMAGES_PATH . $hashName . '.' . $this->images->extension; if (!$this->images->saveAs($fullImagePath)) { throw new \Exception('Image not save in full image path'); } $imgSizeReduct = function ($side = 'width') use($fullImagePath) { $size = getimagesize($fullImagePath); if ($side === 'width') { return $size[0] / self::THUMB_REDUCTION; } if ($side === 'height') { return $size[1] / self::THUMB_REDUCTION; } }; $images = new Images(); $transformation = new Transformation(); $imagine = new Imagine(); $transformation->thumbnail(new Box($imgSizeReduct('width'), $imgSizeReduct('height')))->save(Yii::getAlias('@webroot/' . self::THUMBS_IMAGES_PATH . $hashName . '.' . $this->images->extension)); $transformation->apply($imagine->open(Yii::getAlias('@webroot/' . self::FULL_IMAGES_PATH . $hashName . '.' . $this->images->extension))); $images->product_id = $products->id; $images->img_name = $hashName . '.' . $this->images->extension; if (!$images->save(false)) { throw new \Exception('Images not save, transaction rollback'); } $transaction->commit(); Yii::$app->session->addFlash('success', 'Product successfully added'); } catch (\Exception $e) { $transaction->rollBack(); throw $e; } }
protected function prepareText($post) { /*Если не указан main_pic то найдем првй попавшейся по посту и поставим*/ if (empty($post['main_pic']) && !empty($post['id'])) { $img_arr = Images::items($post['id']); /*Если что то найдет то вставит*/ if (!empty($img_arr)) { reset($img_arr); $img_arr = current($img_arr); $post['main_pic'] = $img_arr['file_name']; } } elseif (!empty($post['main_pic'])) { $post['main_pic'] = explode("/", $post['main_pic']); $post['main_pic'] = end($post['main_pic']); $post['main_pic'] = trim($post['main_pic']); } /**подготавливаем текст для сохранения*/ $post['full_text'] = $post['content']; if ($str_res = strpos($post['full_text'], '<!--more-->')) { $post['text_preview'] = substr($post['full_text'], 0, $str_res); } else { $post['full_text'] = strip_tags($post['full_text']); $post['text_preview'] = substr($post['full_text'], 0, 400); if ($str_res = strripos($post['text_preview'], ' ')) { $post['text_preview'] = substr($post['text_preview'], 0, $str_res); } } $post['full_text'] = str_replace('<!--more-->', " ", $post['content']); return $post; }
static function GetImagePath($id, $type, $suffix) { $fileName = md5(time() . $id . "_" . $suffix); $storePath = Images::IMAGE_STORE_ROOT_PATH . $type . "/" . Images::Kmod($id) . "/"; $webPath = Images::IMAGE_WEB_ROOT_PATH . $type . "/" . Images::Kmod($id) . "/" . $fileName; return array($storePath, $fileName, $webPath); }
public function run($class_name) { $path = realpath(Yii::app()->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $class_name); $class_name = ucfirst($class_name); if ($path && is_dir($path) && is_writable($path)) { $dir = key($_GET); $filename = $_GET[$dir]; $pk = pathinfo($filename, PATHINFO_FILENAME); $image = Images::model()->findByPk($pk); if ($image != null) { $image->resize($dir); } } elseif (class_exists($class_name)) { $dir = key($_GET); $filename = $_GET[$dir]; $size = explode('x', $dir); $path = realpath(Yii::app()->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $class_name); if (YII_DEBUG && !file_exists($path . DIRECTORY_SEPARATOR . $dir)) { mkdir($path . DIRECTORY_SEPARATOR . $dir, 0777); } if ($path !== FALSE && file_exists($path . DIRECTORY_SEPARATOR . $dir) && is_file($path . DIRECTORY_SEPARATOR . $filename) && $size[0] > 0 && $size[1] > 0) { Yii::import('ext.iwi.Iwi'); $image = new Iwi($path . DIRECTORY_SEPARATOR . $filename); $image->adaptive($size[0], $size[1]); $image->save($path . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $filename, 0644, TRUE); $mime = CFileHelper::getMimeType($path . DIRECTORY_SEPARATOR . $filename); header('Content-Type: ' . $mime); $image->render(); exit; } } return parent::run($class_name); }
/** * Load image info based on the id */ public function getImageInfo($id) { $image = Images::findFirst($id); if (!$image) { die('image not found!'); } $sql = 'select x, y, value, name as text FROM images_tags left join tags on images_tags.tag_id = tags.id WHERE confidence is null AND images_tags.image_id = ' . $id; $resultSet = $this->getDI()->get('db')->query($sql); $resultSet->setFetchMode(Phalcon\Db::FETCH_ASSOC); //Get tags $tags = $image->getTags()->toArray(); //Get imageTags $imageTags = $image->getImagesTags()->toArray(); $result = []; $result['image'] = $image; //Add tags $result['tags'] = $resultSet->fetchAll(); //Load additional information $additionalDataSql = 'select * from additional_image_info a WHERE a.filename = \'' . $image->filename . '\' LIMIT 1'; $resultSet2 = $this->getDI()->get('db')->query($additionalDataSql); $resultSet2->setFetchMode(Phalcon\Db::FETCH_ASSOC); $addData = $resultSet2->fetchAll(); //The data added depends on the type of information present if (isset($addData[0])) { $result['additional_info'] = $addData[0]; } else { $result['additional_info'] = []; $result['additional_info']['fotograf'] = null; } //Adds a default photographer if no name is given if ($result['additional_info']['fotograf'] == null || $result['additional_info']['fotograf'] == '' || $result['additional_info']['fotograf'] == '?') { $result['additional_info']['fotograf'] = 'DR'; } return $result; }
public function savePost() { $post = ['title' => Input::get('title'), 'content' => Input::get('content'), 'picture' => Input::get('picture')]; $rules = ['title' => 'required', 'content' => 'required']; $valid = Validator::make($post, $rules); if ($valid->passes()) { $post = new Post($post); $post->comment_count = 0; $post->read_more = strlen($post->content) > 120 ? substr($post->content, 0, 120) : $post->content; /* $destinationPath = 'uploads'; // upload path //$extension = Input::file('image')->getClientOriginalExtension(); // getting image extension $fileName = time(); // renameing image Input::file('images')->make($destinationPath, $fileName); // uploading file to given path $post->images = Input::get($fileName); $pic = Input::file('picture'); $pic_name = time(); Image::make($pic)->save(public_path().'/images/300x'.$pic_name); $post->images = '/images/'.'300x'.$pic_name; $post->images = Input::get($pic_name); */ $file = Request::file('picture'); $extension = $file; Images::disk('local')->put($file->getFilename() . '.' . $extension, File::get($file)); $post->images = $file->time(); $post->save(); return Redirect::to('admin/dash-board')->with('success', 'Post is saved!'); } else { return Redirect::back()->withErrors($valid)->withInput(); } }
function add($request, $response, $args) { $body = $request->getParsedBody(); if (!isset($_FILES['image'])) { echo "No files uploaded!!"; return; } $name = $_FILES['image']['name']; if (move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $name) === true) { $url = 'uploads/' . $name; } $image = new Images(); $image->title = $body['title']; $image->url = $url; $image->save(); }
public function actionConvert() { @set_time_limit(0); @ini_set('max_execution_time', 0); $sql = 'SELECT id, owner_id FROM {{apartment}} WHERE 1'; $res = Yii::app()->db->createCommand($sql)->queryAll(); $ids = CHtml::listData($res, 'id', 'owner_id'); $sql = 'SELECT pid, imgsOrder FROM {{galleries}} WHERE 1'; $res = Yii::app()->db->createCommand($sql)->queryAll(); if ($res) { foreach ($res as $item) { $images = unserialize($item['imgsOrder']); if (!isset($ids[$item['pid']])) { continue; } if ($images) { $cnt = 0; foreach ($images as $image => $name) { $filePath = Yii::getPathOfAlias('webroot.uploads.apartments.' . $item['pid'] . '.pictures') . '/' . $image; Images::addImage($filePath, $item['pid'], $cnt == 0, $ids[$item['pid']]); $cnt++; } } } } }
/** * list images * * @param resource the SQL result * @return string the rendered text * * @see layouts/layout.php **/ function layout($result) { global $context; // empty list if (!SQL::count($result)) { $output = array(); return $output; } // we return an array of ($url => $attributes) $items = array(); // process all items in the list while ($item = SQL::fetch($result)) { // url to view the image $url = Images::get_url($item['id']); // initialize variables $prefix = $suffix = ''; // flag new images if ($item['edit_date'] >= $context['fresh']) { $suffix .= NEW_FLAG; } // image title or image name $label = Skin::strip($item['title'], 10); if (!$label) { $name_as_title = TRUE; $label = ucfirst($item['image_name']); } $label = str_replace('_', ' ', str_replace('%20', ' ', $label)); // list all components for this item $items[$url] = array($prefix, $label, $suffix, 'basic', NULL); } // end of processing SQL::free($result); return $items; }
/** * Store a newly created user in storage. * @param Request $request * @return Response */ public function store(Request $request) { $this->checkPermission('users-manage'); $validationRules = ['name' => 'required', 'email' => 'required|email|unique:users,email']; $authMethod = config('auth.method'); if ($authMethod === 'standard') { $validationRules['password'] = '******'; $validationRules['password-confirm'] = 'required|same:password'; } elseif ($authMethod === 'ldap') { $validationRules['external_auth_id'] = 'required'; } $this->validate($request, $validationRules); $user = $this->user->fill($request->all()); if ($authMethod === 'standard') { $user->password = bcrypt($request->get('password')); } elseif ($authMethod === 'ldap') { $user->external_auth_id = $request->get('external_auth_id'); } $user->save(); if ($request->has('roles')) { $roles = $request->get('roles'); $user->roles()->sync($roles); } // Get avatar from gravatar and save if (!config('services.disable_services')) { $avatar = \Images::saveUserGravatar($user); $user->avatar()->associate($avatar); $user->save(); } return redirect('/settings/users'); }
function ThumbMaker() { global $path; // Создаем массив с которым будем работать; // Если существуют оба массива; if (count($_SESSION['good_dbimages_file']) > 0 and count($_SESSION['good_images_file']) > 0) { $working_array = array_merge($_SESSION['good_dbimages_file'], $_SESSION['good_images_file']); goto make_thumb; } // Если существует только один массив; if (count($_SESSION['good_dbimages_file']) > 0) { $working_array = $_SESSION['good_dbimages_file']; } if (count($_SESSION['good_images_file']) > 0) { $working_array = $_SESSION['good_images_file']; } make_thumb: if (isset($working_array)) { // Функция для сортировки массива по положению фотографий; function sortBy($arr, $sortKey) { // Временный массив для сотритовки по нужному ключу; $tempArr = array(); // Возвращаемый массив; $returnArr = array(); // Перебор всего массива; foreach ($arr as $key => $value) { // Запись в массив значений ключа по которому быдет выполнена сортировка; $tempArr[$key] = $value[$sortKey]; } // Сортировка значений с сохранением ключей; asort($tempArr); // Установка указателя массива не первый элемент; reset($tempArr); // Перебор всего временного массива; foreach ($tempArr as $key => $value) { // Формирование возвращаемого массива; $returnArr[] = $arr[$key]; } return $returnArr; } $new_array = sortBy($working_array, 'position'); $thumb_images = new Images(); $thumb_images->Thumber($new_array, $path, 200, 200, 1, 1, 1); return $thumb_images->result; } }
public function loadModel($id) { $model = Images::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'Страница не найдена'); } return $model; }
public function run() { if (!$this->images) { $sql = 'SELECT id, file_name, comment, id_object, file_name_modified, is_main FROM {{images}} WHERE id_object=:id ORDER BY sorter'; $this->images = Images::model()->findAllBySql($sql, array(':id' => $this->objectId)); } $this->render('widgetAdminViewImages', array('images' => $this->images)); }
/** * list images * * @param resource the SQL result * @return string the rendered text * * @see layouts/layout.php **/ function layout($result) { global $context; // empty list if (!SQL::count($result)) { $output = array(); return $output; } // we return an array of ($url => $attributes) $items = array(); // process all items in the list while ($item = SQL::fetch($result)) { // get the anchor for this image if ($item['anchor']) { $anchor = Anchors::get($item['anchor']); } // url to view the image $url = $context['url_to_home'] . $context['url_to_root'] . Images::get_url($item['id']); // time of last update $time = SQL::strtotime($item['edit_date']); // the title as the label if ($item['title']) { $label = ucfirst($item['title']) . ' (' . $item['image_name'] . ')'; } else { $label = $item['image_name']; } // the section $section = ''; if (is_object($anchor)) { $section = ucfirst($anchor->get_title()); } // the author(s) is an e-mail address, according to rss 2.0 spec $author = $item['create_address'] . ' (' . $item['create_name'] . ')'; if ($item['create_address'] != $item['edit_address']) { if ($author) { $author .= ', '; } $author .= $item['edit_address'] . ' (' . $item['edit_name'] . ')'; } // the description $description = Codes::beautify($item['description']); // cap the number of words $description = Skin::cap($description, 300); // fix image references $description = preg_replace('#"/([^">]+?)"#', '"' . $context['url_to_home'] . '/$1"', $description); $introduction = $description; // other rss fields $extensions = array(); // url for enclosure $type = Files::get_mime_type($item['image_name']); $extensions[] = '<enclosure url="' . $context['url_to_home'] . $context['url_to_root'] . Files::get_path($item['anchor'], 'images') . '/' . $item['image_name'] . '"' . ' length="' . $item['image_size'] . '"' . ' type="' . $type . '" />'; // list all components for this item $items[$url] = array($time, $label, $author, $section, NULL, $introduction, $description, $extensions); } // end of processing SQL::free($result); return $items; }
public static function getImage($imageOfId, $entityId) { $model = Images::model()->find('image_of_id=:imageOfId AND entity_id=:entityId', array(':imageOfId' => $imageOfId, ':entityId' => $entityId)); if ($model) { return $model->filename; } else { return false; } }
public function actionUpload($id) { $model = $this->checkOwner($id); Yii::import("ext.EAjaxUpload.qqFileUploader"); $allowedExtensions = param('allowedImgExtensions', array('jpg', 'jpeg', 'gif', 'png')); //$sizeLimit = param('maxImgFileSize', 8 * 1024 * 1024); $sizeLimit = Images::getMaxSizeLimit(); $uploader = new qqFileUploader($allowedExtensions, $sizeLimit); $path = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::ORIGINAL_IMG_DIR); $pathMod = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::MODIFIED_IMG_DIR); $oldUMask = umask(0); if (!is_dir($path)) { @mkdir($path, 0777, true); } if (!is_dir($pathMod)) { @mkdir($pathMod, 0777, true); } umask($oldUMask); if (is_writable($path) && is_writable($pathMod)) { touch($path . DIRECTORY_SEPARATOR . 'index.htm'); touch($pathMod . DIRECTORY_SEPARATOR . 'index.htm'); $result = $uploader->handleUpload($path . DIRECTORY_SEPARATOR, false, uniqid()); if (isset($result['success']) && $result['success']) { $resize = new CImageHandler(); if ($resize->load($path . DIRECTORY_SEPARATOR . $result['filename'])) { $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)->save(); $image = new Images(); $image->id_object = $model->id; $image->id_owner = $model->owner_id; $image->file_name = $result['filename']; $image->save(); } else { $result['error'] = 'Wrong image type.'; @unlink($path . DIRECTORY_SEPARATOR . $result['filename']); } } } else { $result['error'] = 'Access denied.'; } // to pass data through iframe you will need to encode all html tags $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES); echo $result; }
public function actionIndex() { $this->pageTitle = $this->dataSystem->title; // Dang ky Internet $criInternet = new CDBCriteria(); $criInternet->addCondition("category_news_id = 1"); $criInternet->order = "id DESC"; $criInternet->limit = 3; $arrInternet = News::model()->findAll($criInternet); //Dang ky cap quang $criOptical = new CDBCriteria(); $criOptical->addCondition("category_news_id = 2"); $criOptical->order = "id DESC"; $criOptical->limit = 3; $arrOptical = News::model()->findAll($criOptical); //Store $criStore = new CDBCriteria(); $criStore->addCondition("category_news_id = 6"); $criStore->order = "id DESC"; $criStore->limit = 3; $arrStore = News::model()->findAll($criStore); //CA $criCa = new CDBCriteria(); $criCa->addCondition("category_news_id = 3"); $criCa->order = "id DESC"; $criCa->limit = 3; $arrCa = News::model()->findAll($criCa); //Sim - Card $criSimCard = new CDBCriteria(); $criSimCard->addCondition("category_news_id = 4"); $criSimCard->order = "id DESC"; $criSimCard->limit = 3; $arrSimCard = News::model()->findAll($criSimCard); //TV $criTv = new CDBCriteria(); $criTv->addCondition("category_news_id = 7"); $criTv->order = "id DESC"; $criTv->limit = 3; $arrTv = News::model()->findAll($criTv); /*Pictures*/ $criPic = new CDbCriteria(); $criPic->addCondition("album_id = 2"); $criPic->order = "id DESC"; $criPic->limit = 10; $arrPic = Images::model()->findAll($criPic); /*Slider*/ $criBanner = new CDbCriteria(); $criBanner->order = "id DESC"; $criBanner->limit = 5; $arrBanner = Slides::model()->findAll($criBanner); /*Links web*/ $arrLink = Links::model()->find(); $this->render("index", array('arrBanner' => $arrBanner, 'arrInternet' => $arrInternet, 'arrOptical' => $arrOptical, 'arrStore' => $arrStore, 'arrCa' => $arrCa, 'arrSimCard' => $arrSimCard, 'arrTv' => $arrTv, 'arrLink' => $arrLink)); }
public function actionCreate() { $model = new DatasetAttributes(); $att = Attribute::model()->findByAttributes(array('attribute_name' => Attribute::FUP)); if (!$att) { $att = new Attribute(); $att->attribute_name = Attribute::FUP; $att->definition = ''; $att->save(); } $model->attribute_id = $att->id; $image = new Images(); if (isset($_POST['DatasetAttributes'])) { $args = $_POST['DatasetAttributes']; $exist = DatasetAttributes::model()->findByAttributes(array('dataset_id' => $args['dataset_id'], 'attribute_id' => $att->id)); if ($exist) { $model = $exist; } $model->attributes = $args; $model->value = ''; //$image->attributes = $_POST['Images']; $image->license = "no license"; $image->photographer = "no author"; $image->source = "gigadb"; if ($image->validate()) { $image->save(); } else { Yii::log(print_r($image->getErrors(), true), 'debug'); } if ($image) { $model->image_id = $image->id; } if ($model->validate()) { $model->save(); $this->redirect('/dataset/' . $model->dataset->identifier); } else { Yii::log(print_r($model->getErrors(), true), 'debug'); } } $this->render('create', array('model' => $model, 'image' => $image)); }
public function actionDelete($id) { $model = Images::model()->findByPk($id); $name = $model->attributes['image']; $this->loadModel($id)->delete(); unlink(Yii::app()->basePath . '/../upload/images/' . $name); Yii::app()->user->setFlash('success', translate('Xóa thành công.')); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) { $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } }
/** * Creates a new user and attaches a role to them. * @param array $data * @return User */ public function registerNew(array $data) { $user = $this->create($data); $this->attachDefaultRole($user); // Get avatar from gravatar and save if (!config('services.disable_services')) { $avatar = \Images::saveUserGravatar($user); $user->avatar()->associate($avatar); $user->save(); } return $user; }
public function actionInsert() { if (isset($_POST['choose'])) { $post = new Posts(); $post->status = 0; $post->updated_at = time(); $post->created_at = time(); $post->user_id = 1; $post->post_content = $_POST['caption']; $post->save(FALSE); $image = new Images(); $image->created_at = time(); $image->updated_at = time(); $image->post_id = $post->post_id; $image->created_by = 1; $image->img_url = $_POST['image_standard_url']; $image->status = 0; $image->save(FALSE); } echo CJSON::encode(array('message' => 'success')); }
public function invokeHandler(Smarty $viewModel, Header $header, User $user, $uname, $upass) { $header->title('PayPic'); $header->import('jqgeeks/bootstrap_css', 'google_login'); $viewModel->assign("pname", "@RTPic"); if ($user->auth($uname, $upass)) { include_once HANDLER_PATH . "/Images.php"; return Images::showlatest($viewModel); } else { return "login"; } }
/** * $image : string */ function image_url($image, $type = null, $force_no_base = false, $use_temp = false, $new_ext = null) { if (!is_null($type)) { $images_types = sfConfig::get('app_images_types'); $suffix = $images_types[$type]['suffix']; } else { $suffix = ''; } list($image_name, $image_ext) = Images::getFileNameParts($image); $base_path = $force_no_base ? '' : sfConfig::get('app_static_url'); $base_path .= DIRECTORY_SEPARATOR . sfConfig::get('app_upload_dir') . DIRECTORY_SEPARATOR . ($use_temp ? sfConfig::get('app_images_temp_directory_name') : sfConfig::get('app_images_directory_name')) . DIRECTORY_SEPARATOR; return $base_path . $image_name . $suffix . (isset($new_ext) ? $new_ext : $image_ext); }
public function uploadImages() { if ($this->validate()) { $transformation = new Transformation(); $imagine = new Imagine(); //$randHeight = function() { //return rand(250, 330); //}; foreach ($this->imageFiles as $file) { /* @var $file \yii\web\UploadedFile */ $imageRandName = Yii::$app->security->generateRandomString(12); $fullImagePath = self::FULL_IMAGES_PATH . $imageRandName . '.' . $file->extension; $file->saveAs($fullImagePath); $imgSizeReduct = function ($side = 'width') use($fullImagePath) { $size = getimagesize($fullImagePath); if ($side === 'width') { return $size[0] / self::THUMB_REDUCTION; } if ($side === 'height') { return $size[1] / self::THUMB_REDUCTION; } }; $transformation->thumbnail(new Box($imgSizeReduct(), $imgSizeReduct('height')))->save(Yii::getAlias('@webroot/' . self::THUMBS_IMAGES_PATH . $imageRandName . '.' . $file->extension)); $transformation->apply($imagine->open(Yii::getAlias('@webroot/' . self::FULL_IMAGES_PATH . $imageRandName . '.' . $file->extension))); $images = new Images(); $images->name = $imageRandName . '.' . $file->extension; $images->alt = $this->alt; if (!$images->save()) { Yii::$app->session->addFlash('danger', 'Image not saved into data base!'); return false; } } Yii::$app->session->addFlash('success', 'Image uploaded successfully'); return true; } Yii::$app->session->addFlash('danger', 'Incorrect data'); return false; }
public function post_upload($galleryID) { $path = path('public') . 'images/' . $galleryID; Fineuploader::init($path); $name = Fineuploader::getName(); $fuResponse = Fineuploader::upload($name); if (isset($fuResponse['success']) && $fuResponse['success'] == true) { $file = Fineuploader::getUploadName(); Bundle::start('resizer'); $success = Resizer::open($file)->resize(300, 300, 'landscape')->save($path . '/thumbs/' . $name, 90); Images::create($galleryID, $name); } return Response::json($fuResponse); }
public function getImagePreviewByPostId($post_id) { $criteria = new CDbCriteria(); $criteria->limit = 1; $criteria->condition = "post_id = {$post_id}"; $data = Images::model()->find($criteria); if ($data) { $url = $data->img_url; return StringHelper::generateUrlImage($url); //Yii::app()->request->getBaseUrl(true) . '/' . $url; } else { return ''; } }
public function guardar() { $nombrearchivo = $_FILES["imagen"]['name']; if ($nombrearchivo != "") { if ($ext = explode('.', $nombrearchivo)) { $nombresinext = reset($ext); $ext = '.' . end($ext); } else { $ext = NULL; } if (!is_dir(APP_IMGS)) { mkdir(APP_IMGS . '/', 0777, true); } $path = APP_IMGS . '/'; $archivo = Upload::factory("imagen", 'file'); $archivo->setPath($path); $archivo->setExtensions(array('jpg', 'jpeg', 'png')); //le asignamos las extensiones a permitir $archivo->setMaxSize('10485760'); //le asignamos el tamaño maximo del archivo $archivo->overwrite($nombresinext, true); //fijamos que pueda sobreescribir el requisito si lo actualiza*/ if ($archivo->isUploaded()) { $archivo->save($nombresinext); $images = new Images(); $images->direc_fisica = APP_IMGSPUBLIC . $nombresinext . $ext; $images->direc_acortada = ''; $images->time = date('Y-m-d h:m'); $images->save(); Flash::valid('Guardado exitosamente'); } else { Flash::warning('No se ha Podido Subir la imagen'); } } Redirect::to('/'); }