/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $image_name = $this->temp_path . $model->{$this->uploadParam}->name; $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name); // watermark if ($this->watermark != '') { $image = Image::watermark($image_name, $this->watermark)->save($image_name); } if ($image->save($image_name)) { // create Thumbnail if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) { Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name); } $result = ['filelink' => $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST')); } }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if (!empty($post['method'])) { $file = basename($post['file']); if (file_exists($this->getPath() . $file)) { unlink($this->getPath() . $file); } } else { $image = \yii\web\UploadedFile::getInstanceByName('upload'); if (!empty($image)) { $imageFileType = strtolower(pathinfo($image->name, PATHINFO_EXTENSION)); $allowed = ['png', 'jpg', 'gif', 'jpeg']; if (!empty($image) and in_array($imageFileType, $allowed)) { $fileName = $this->getFileName($image); $image->saveAs($this->getPath() . $fileName); $imagine = Image::getImagine(); $photo = $imagine->open($this->getPath() . $fileName); $photo->thumbnail(new Box($this->maxWidth, $this->maxHeight))->save($this->getPath() . $fileName, ['quality' => 90]); } } } } $data['url'] = $this->getUrl(); $data['path'] = $this->getPath(); $data['ext'] = $this->getFileExt(); BrowseAssets::register($this->controller->view); $this->controller->layout = '@vendor/bajadev/yii2-ckeditor/views/layout/image'; return $this->controller->render('@vendor/bajadev/yii2-ckeditor/views/browse', ['data' => $data]); }
public function upload($attribute) { $class = \yii\helpers\StringHelper::basename(get_class($this->owner)) . 'Cutter'; if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) { if (!$this->owner->isNewRecord) { $this->delete($attribute); } $cropping = $_POST[$class][$attribute . '-cropping']; $croppingFileName = md5($uploadImage->name . $this->quality . Json::encode($cropping)); $croppingFileExt = strrchr($uploadImage->name, '.'); $croppingFileDir = substr($croppingFileName, 0, 2); $croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir; if (!is_dir($croppingFileBasePath)) { mkdir($croppingFileBasePath, 0755, true); } $croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir; if (!is_dir($croppingFilePath)) { mkdir($croppingFilePath, 0755, true); } $fileSavePath = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; $point = new Point($cropping['dataX'], $cropping['dataY']); $box = new Box($cropping['dataWidth'], $cropping['dataHeight']); $palette = new \Imagine\Image\Palette\RGB(); $color = $palette->color('fff', 0); Image::frame($uploadImage->tempName, 0, 'fff', 0)->rotate($cropping['dataRotate'], $color)->crop($point, $box)->save($fileSavePath, ['quality' => $this->quality]); $this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; } elseif (isset($_POST[$class][$attribute . '-remove']) && $_POST[$class][$attribute . '-remove']) { $this->delete($attribute); } elseif (!empty($_POST[$class][$attribute])) { $this->owner->{$attribute} = $_POST[$class][$attribute]; } elseif (isset($this->owner->oldAttributes[$attribute])) { $this->owner->{$attribute} = $this->owner->oldAttributes[$attribute]; } }
public function run() { if (Yii::$app->request->isPost) { $data = Yii::$app->request->post(); if (!empty($data['url']) && in_array($data['direction'], ['CW', 'CCW'])) { try { $url = $data['url']; $url = str_replace(Yii::$app->request->baseUrl, '', $url); if (substr($url, 0, 1) == '/') { $url = substr($url, 1); } if (strpos($url, '?_ignore=') !== false) { $url = substr($url, 0, strpos($url, '?_ignore=')); } Image::getImagine()->open($url)->copy()->rotate($data['direction'] == 'CW' ? 90 : -90)->save($url); list($width, $height) = getimagesize($url); return Json::encode(['size' => [$width, $height], 'url' => Yii::$app->request->baseUrl . '/' . $url]); } catch (Exception $e) { return Json::encode(['errors' => [$e->getMessage()]]); } } else { return Json::encode(['errors' => ['Invalid rotate options!']]); } } }
public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($file = UploadedFile::getInstance($this, 'photo')) { $imgPath = Yii::getAlias('@storage/teachers/') . $this->photo; if (is_file($imgPath)) { unlink($imgPath); } $imgName = Yii::$app->getSecurity()->generateRandomString(8); $img = $imgName . '.' . $file->extension; if (!file_exists(Yii::getAlias('@storage/teachers/'))) { mkdir(Yii::getAlias('@storage/teachers/'), 0777, true); } //save temp file if ($file->saveAs(Yii::getAlias('@runtime/') . $img, true)) { Image::thumbnail('@runtime/' . $img, 200, 200)->save(Yii::getAlias('@storage/teachers/' . $img), ['quality' => 100]); $this->photo = $img; //delete temp file unlink(Yii::getAlias('@runtime/') . $img); } else { throw new \yii\web\HttpException(500, 'не удалось сохранить изображение ' . $file->baseName . '.' . $file->extension); } } return true; } else { return false; } }
/** * @return bool */ public function upload() { if ($this->validate()) { $model = UserProfile::findOne(['user_id' => Yii::$app->user->identity->getId()]); if (!$model) { $model = new UserProfile(); $model->user_id = Yii::$app->user->identity->getId(); } $path = $this->getUserDirectory($model->user_id); $file = $this->imageFile; //удаляем старую аватарку if ($model->avatar) { $avatar = $path . '/' . $model->avatar; if (file_exists($avatar)) { unlink($avatar); } } $name = time() . '.' . $file->extension; //$file->imageFile->baseName $tmp = '_' . $name; if ($file->saveAs($path . '/' . $tmp)) { $model->avatar = $name; Image::thumbnail($path . '/' . $tmp, 100, 100)->save($path . '/' . $model->avatar, ['quality' => 80]); if (file_exists($path . '/' . $tmp)) { unlink($path . '/' . $tmp); } $model->save(); } return true; } else { return false; } }
public function put($file_name, $thumbnail = FALSE, $copy = FALSE) { // Проверяем наличие файла if (file_exists($file_name)) { // Получаем расширение $file = explode(".", $file_name); $ext = $file[count($file) - 1]; // Формируем имя файла в хранилище $md_name = md5_file($file_name); $md_name = $md_name . '.' . $ext; if ($thumbnail) { $patch = $this->_storagePath($md_name, DIR_IMAGE . 'thumb') . '/' . $md_name; Image::thumbnail($file_name, 120, 120)->save(Yii::getAlias($patch), ['quality' => 80]); } else { $patch = $this->_storagePath($md_name, DIR_IMAGE) . '/' . $md_name; rename($file_name, $patch); } /*if ($copy) { // Копируем файл в хранилище под новым именем copy($file_name, $patch); } else { // Перемещаем файл в хранилище под новым именем rename($file_name, $patch); } */ return $md_name; } else { return FALSE; } }
/** * Creates thumb from model->image attribute with specified width and height. * @param int|null $width * @param int|null $height * @param bool $crop if false image will be resize instead of cropping * @return string */ public function thumb($width = null, $height = null, $crop = true) { if ($this->image && ($width || $height)) { return Image::thumbnail($this->image, $width, $height, $crop); } return ''; }
/** * Скропать изображения и вернуть объет для работы с ним. * * Если исходное изображение меньше по размерам - сначала его ресайзит до нужных размеров. * * @param string $tmpFileName Путь к исходному файлу * @param integer $paramWidth Ширина для кропа * @param integer $paramHeight Высота для кропа * * @return ImageInterface */ public static function cropImage($tmpFileName, $paramWidth, $paramHeight) { $newImage = Image::getImagine()->open($tmpFileName); $imageSizes = $newImage->getSize(); $width = $imageSizes->getWidth(); $height = $imageSizes->getHeight(); //Если меньше нужных размеров, то сначала пропорционально ресайзим if ($width < $paramWidth || $height < $paramHeight) { $newHeight = $height; $newWidth = $width; if ($width / $height > $paramWidth / $paramHeight) { $newHeight = $paramHeight; $newWidth = round($newHeight * $width / $height); } elseif ($width / $height <= $paramWidth / $paramHeight) { $newWidth = $paramWidth; $newHeight = round($newWidth * $height / $width); } $newImage->resize(new Box($newWidth, $newHeight))->save($tmpFileName, ['quality' => 80]); } $box = new Box($paramWidth, $paramHeight); if ($newImage->getSize()->getWidth() <= $box->getWidth() && $newImage->getSize()->getHeight() <= $box->getHeight() || !$box->getWidth() && !$box->getHeight()) { return $newImage->copy(); } $newImage = $newImage->thumbnail($box, ManipulatorInterface::THUMBNAIL_OUTBOUND); // create empty image to preserve aspect ratio of thumbnail $thumb = Image::getImagine()->create(new Box($newImage->getSize()->getWidth(), $newImage->getSize()->getHeight()), new Color('FFF', 100)); $thumb->paste($newImage, new Point(0, 0)); return $thumb; }
public function actionUpdate($id) { $model = $this->findModelById($id); $current_image = $model->image; if ($model->load(Yii::$app->request->post())) { $file = UploadedFile::getInstance($model, 'image'); if ($file && $file->tempName) { $model->file = $file; if ($model->validate(['file'])) { if ($model->delImage) { if (file_exists(Yii::getAlias('@webroot' . $current_image))) { //удаляем файл unlink(Yii::getAlias('@webroot' . $current_image)); $model->image = null; } } $dir = Yii::getAlias('images/users'); $fileName = '/' . $model->file->baseName . '.' . $model->file->extension; $model->file->saveAs($dir . $fileName); $model->file = $fileName; Image::thumbnail($dir . $fileName, 70, 70)->save(Yii::getAlias($dir . '/thumbs' . $fileName), ['quality' => 75]); $model->image = '/' . $dir . '/thumbs' . $fileName; } } if ($model->save()) { Yii::$app->getSession()->setFlash('success', 'Профиль изменен.'); return $this->redirect(['index']); } } return $this->render('update', ['model' => $model]); }
public function changePortrait() { $user = User::findOne(Yii::$app->user->identity->id); if (is_null($user)) { $this->addError('portrait', '用户不存在'); return false; } $path = Yii::getAlias("@webroot/portrait/"); $largePath = Yii::getAlias("@webroot/portrait/large/"); $mediumPath = Yii::getAlias("@webroot/portrait/medium/"); $smallPath = Yii::getAlias("@webroot/portrait/small/"); //保存新头像 $filename = date('H.i.s') . '-' . md5($this->portrait->name) . '.' . $this->portrait->extension; $this->portrait->saveAs($path . $filename); //large Image::thumbnail($path . $filename, 220, 220)->save($largePath . $filename); //medium Image::thumbnail($path . $filename, 128, 128)->save($mediumPath . $filename); //small Image::thumbnail($path . $filename, 64, 64)->save($smallPath . $filename); //删除原头像 $oldFilename = $user->portrait; @unlink($path . $oldFilename); @unlink($largePath . $oldFilename); @unlink($mediumPath . $oldFilename); @unlink($smallPath . $oldFilename); //保存新头像名到数据库 $user->portrait = $filename; if (!$user->save(false)) { $this->addError('portrait', '头像修改失败'); return false; } return true; }
/** * fetch image from protected location and manipulate it and copy to public folder to show in front-end * This function cache the fetched image with same width and height before * * @author A.Jafaripur <*****@*****.**> * * @param integer $id image id number to seprate the folder in public folder * @param string $path original image path * @param float $width width of image for resize * @param float $heigh height of image for resize * @param integer $quality quality of output image * @return string fetched image url */ public function getImage($id, $path, $width, $heigh, $quality = 70) { $fileName = $this->getFileName(Yii::getAlias($path)); $fileNameWithoutExt = $this->getFileNameWithoutExtension($fileName); $ext = $this->getFileExtension($fileName); if ($width == 0 && $heigh == 0) { $size = Image::getImagine()->open($path)->getSize(); $width = $size->getWidth(); $heigh = $size->getHeight(); } $newFileName = $fileNameWithoutExt . 'x' . $width . 'w' . $heigh . 'h' . '.' . $ext; $upload_number = (int) ($id / 2000) + 1; $savePath = Yii::getAlias('@webroot/images/' . $upload_number); $baseImageUrl = Yii::$app->getRequest()->getBaseUrl() . '/images/' . $upload_number; FileHelper::createDirectory($savePath); $savePath .= DIRECTORY_SEPARATOR . $newFileName; if ($width == 0 && $heigh == 0) { copy($path, $savePath); } else { if (!file_exists($savePath)) { Image::thumbnail($path, $width, $heigh)->interlace(\Imagine\Image\ImageInterface::INTERLACE_PLANE)->save($savePath, ['quality' => $quality]); } } return $baseImageUrl . '/' . $newFileName; }
public function actionCrop($id) { $model = $this->findModel($id); $type = \Yii::$app->getRequest()->post("type"); $x = \Yii::$app->getRequest()->post("x"); $y = \Yii::$app->getRequest()->post("y"); $w = \Yii::$app->getRequest()->post("w"); $h = \Yii::$app->getRequest()->post("h"); switch ($type) { case CropType::ALL: $original = $model->getAbsolutePath(); Image::crop($original, $w, $h, [$x, $y])->save($original); $model->deleteThumbs(); break; case CropType::THUMBNAIL: $original = $model->getAbsolutePath(); $newPath = $model->getTempDirectory() . DIRECTORY_SEPARATOR . $model->hash . "." . $model->extension; $newOriginal = \Yii::$app->get("fileStorage")->getPath($newPath); Image::crop($original, $w, $h, [$x, $y])->save($newOriginal); $thumbs = $model->getThumbs(); foreach ($thumbs as $path) { $fileName = ltrim(pathinfo(" " . $path, PATHINFO_FILENAME)); $parts = explode("_", $fileName); list($w, $h) = explode("x", $parts[2]); Image::thumbnail($newOriginal, $w, $h)->save(\Yii::$app->get("fileStorage")->getPath($path)); } \Yii::$app->get("fileStorage")->delete($newPath); break; case CropType::ORIGINAL: $original = $model->getAbsolutePath(); Image::crop($original, $w, $h, [$x, $y])->save($original); break; } return $this->renderJsonMessage(true, "裁剪成功"); }
/** * @param $oldModel FileUploadBehavior */ public function afterSave($oldModel) { parent::afterSave($oldModel); if ($this->_file instanceof UploadedFile) { foreach ($this->options['thumbs'] as $id => $options) { if (isset($options['imagine']) || $options['saveOptions']) { if (empty($options['saveOptions'])) { $options['saveOptions'] = []; } if (empty($options['imagine'])) { $options['imagine'] = function ($filename) { return Image::getImagine()->open($filename); }; } $this->processImage($options['imagine'], $options['saveOptions'], $id); } } if (isset($this->options['imagine']) || $this->options['saveOptions']) { if (empty($this->options['saveOptions'])) { $this->options['saveOptions'] = []; } if (empty($this->options['imagine'])) { $this->options['imagine'] = function ($filename) { return Image::getImagine()->open($filename); }; } $this->processImage($this->options['imagine'], $this->options['saveOptions']); } } }
public function upload() { if ($this->validate()) { if ($this->file and $this->file_id != 2) { unlink(Yii::getAlias('images/property-values/thumbs/' . $this->file->ime)); unlink(Yii::getAlias('images/property-values/' . $this->file->ime)); } $fileName = $this->id . '_' . $this->name; $this->imageFile->saveAs('images/property-values/' . $fileName . '1.' . $this->imageFile->extension); $image = new \common\models\Images(); $image->ime = $fileName . '.' . $this->imageFile->extension; $image->type = 'image'; $image->date = date('Y-m-d H:i:s'); $thumb = 'images/property-values/' . $fileName . '1.' . $this->imageFile->extension; Image::thumbnail($thumb, 400, 300)->save(Yii::getAlias('images/property-values/' . $fileName . '.' . $this->imageFile->extension), ['quality' => 80]); Image::thumbnail($thumb, 80, 64)->save(Yii::getAlias('images/property-values/thumbs/' . $fileName . '.' . $this->imageFile->extension), ['quality' => 80]); $image->save(); if ($image->save()) { $this->file_id = $image->id; $this->imageFile = null; $this->save(); } unlink(Yii::getAlias($thumb)); return; } else { return false; } }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $width = $request->post('width', $this->width); $height = $request->post('height', $this->height); $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($width, $height)); if ($image->save($this->path . $model->{$this->uploadParam}->name)) { $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST')); } }
public function uploadImage($route, $gallery_types_id, $gallery_groups_id) { $type = (new Query())->select('*')->from($this->tableTypes)->where(['id' => $gallery_types_id])->createCommand()->queryOne(); $route = preg_replace('/\\/$/', '', $route); $destination = preg_replace('/\\/$/', '', $type['destination']); if (!is_dir($route . $destination)) { if (!mkdir($route . $destination)) { return ['success' => false, 'message' => 'Failed to add directory']; } } $imageFile = UploadedFile::getInstanceByName('image'); $image = (new Query())->select('*')->from($this->tableImages)->where(['gallery_groups_id' => $gallery_groups_id])->andWhere(['name' => $imageFile->baseName . '.' . $imageFile->extension])->createCommand()->queryOne(); if ($image) { return ['success' => false, 'message' => 'File downloaded previously in this group']; } $src_file = $route . $destination . '/' . $imageFile->baseName . '.' . $imageFile->extension; $imageFile->saveAs($src_file, true); $size = $this->getSize($src_file, $type); $image_small = $this->renderFilename($route . $destination, $imageFile->extension); $image_large = $this->renderFilename($route . $destination, $imageFile->extension); Image::$driver = [Image::DRIVER_GD2]; Image::thumbnail($src_file, $size['small_width'], $size['small_height'])->save($route . $destination . '/' . $image_small . '.' . $imageFile->extension, ['quality' => $type['quality']]); Image::thumbnail($src_file, $size['large_width'], $size['large_height'])->save($route . $destination . '/' . $image_large . '.' . $imageFile->extension, ['quality' => $type['quality']]); unlink($src_file); $query = new Query(); $query->createCommand()->insert($this->tableImages, ['gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension, 'name' => $imageFile->baseName . '.' . $imageFile->extension, 'seq' => $this->getLastSequence($gallery_groups_id) + 1])->execute(); return ['success' => true, 'gallery_images_id' => Yii::$app->db->getLastInsertID(), 'gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension]; }
/** * Lists all MetaBase models. * @return mixed */ public function actionIndex() { $model = new Icon(); if (Yii::$app->request->isPost) { $model->imageOriginal = UploadedFile::getInstance($model, 'imageOriginal'); $model->imageDelete = Yii::$app->request->Post('Icon')['imageDelete']; if ($model->imageOriginal && $model->validate()) { if (!file_exists($model->pathForIcons)) { mkdir($model->pathForIcons, 0777, true); } $model->imageOriginal->saveAs($model->pathForIcons . '/apple-icon-original.' . $model->imageOriginal->extension); if ($model->imageOriginal) { if (!file_exists($model->pathForIcons)) { mkdir($model->pathForIcons, 0777, true); } Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 60, 60)->save($model->pathForIcons . '/apple-touch-icon.png'); Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 76, 76)->save($model->pathForIcons . '/apple-touch-icon-76x76.png'); Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 120, 120)->save($model->pathForIcons . '/apple-touch-icon-120x120.png'); Image::thumbnail($model->pathForIcons . '/apple-icon-original.png', 152, 152)->save($model->pathForIcons . '/apple-touch-icon-152x152.png'); $this->redirect(Url::to()); } } else { $model->delete(); $this->redirect(Url::to()); } } return $this->render('index', ['model' => $model]); }
public static function saveImage($model) { $model->date = date('Y-m-d'); $maxId = Products::find()->select('max(id)')->scalar(); $imageName = $maxId + 1; // (uniqid('img_')-как вариант, без нагрузки на бд)лучше вариант чем с датой, primary key всегда будет // уникальным + запрос вроде не сложный на выборку поскольку primary индексированый и взять максимальное // не составит большую нагрузку на бд $model->photo = UploadedFile::getInstance($model, 'photo'); $fullName = Yii::getAlias('@webroot') . '/photos/' . $imageName . '.' . $model->photo->extension; $model->photo->saveAs($fullName); $img = Image::getImagine()->open($fullName); $size = $img->getSize(); $ratio = $size->getWidth() / $size->getHeight(); $height = round(Products::IMAGE_WIDTH / $ratio); $box = new Box(Products::IMAGE_WIDTH, $height); $img->resize($box)->save(Yii::getAlias('@webroot') . '/thumbnails/' . $imageName . '.' . $model->photo->extension); $model->thumbnail = '/thumbnails/' . $imageName . '.' . $model->photo->extension; $model->photo = '/photos/' . $imageName . '.' . $model->photo->extension; $save = $model->save(); if ($save) { return true; } else { die('product model was not save'); } }
public function Uploadphoto($images, $article_id) { $i = 0; // счетчик что определить фотографии когда они загружаются второе изображение может перезаписать первую в ту же секунду. foreach ($images as $file) { $newFileName = date("YmdHis") . $i; $filePath = Yii::getAlias('@frontend') . '/web/uploads/' . $newFileName . '.' . $file->extension; $file427320 = Yii::getAlias('@frontend') . '/web/uploads/427320/' . $newFileName . '.' . $file->extension; $file7070 = Yii::getAlias('@frontend') . '/web/uploads/7070/' . $newFileName . '.' . $file->extension; $file->saveAs($filePath); Image::thumbnail($filePath, 427, 320)->save($file427320, ['quality' => 50]); Image::thumbnail($filePath, 70, 70)->save($file7070, ['quality' => 50]); $image = new article_photo(); $image->article_id = $article_id; $image->photo_path = Yii::getAlias('@resource') . '/uploads/' . $newFileName . '.' . $file->extension; $image->photo_path427320 = Yii::getAlias('@resource') . '/uploads/427320/' . $newFileName . '.' . $file->extension; $image->photo_path7070 = Yii::getAlias('@resource') . '/uploads/7070/' . $newFileName . '.' . $file->extension; $image->alt = ''; if ($image->save()) { $errorLoadFile = true; } else { $errorLoadFile = false; } $i++; } return $errorLoadFile; }
public function upload($attribute) { if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) { if (!$this->owner->isNewRecord) { $this->delete($attribute); } $croppingFileName = md5($uploadImage->name . $this->quality . filemtime($uploadImage->tempName)); $croppingFileExt = strrchr($uploadImage->name, '.'); $croppingFileDir = substr($croppingFileName, 0, 2); $croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir; if (!is_dir($croppingFileBasePath)) { mkdir($croppingFileBasePath, 0755, true); } $croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir; if (!is_dir($croppingFilePath)) { mkdir($croppingFilePath, 0755, true); } $croppingFile = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; $cropping = $_POST[$attribute . '-cropping']; $imageTmp = Image::getImagine()->open($uploadImage->tempName); $imageTmp->rotate($cropping['dataRotate']); $image = Image::getImagine()->create($imageTmp->getSize()); $image->paste($imageTmp, new Point(0, 0)); $point = new Point($cropping['dataX'], $cropping['dataY']); $box = new Box($cropping['dataWidth'], $cropping['dataHeight']); $image->crop($point, $box); $image->save($croppingFile, ['quality' => $this->quality]); $this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; } elseif (isset($_POST[$attribute . '-remove']) && $_POST[$attribute . '-remove']) { $this->delete($attribute); } elseif (isset($this->owner->oldAttributes[$attribute])) { $this->owner->{$attribute} = $this->owner->oldAttributes[$attribute]; } }
/** * Calculate p-hash and save image * @param string $file * @throws Exception * @return Image */ public static function importImage($file) { try { $fileInfo = pathinfo($file); $model = new Image(); $model->md5 = md5_file($file); $model->phash = self::getPHash($file); $model->path = sprintf('%s/%s.%s', substr($model->md5, 0, 2), $model->md5, $fileInfo['extension']); $model->previewPath = sprintf('%s/%s_preview.%s', substr($model->md5, 0, 2), $model->md5, $fileInfo['extension']); if ($model->save()) { $dstImage = Yii::getAlias('@app/web/uploads') . '/' . $model->path; $dstPath = dirname($dstImage); if (!is_dir($dstPath)) { mkdir($dstPath, 0777, true); } if (!file_exists($dstImage)) { copy($file, $dstImage); Imagine::thumbnail($file, 300, 300)->save(Yii::getAlias('@app/web/uploads') . '/' . $model->previewPath, ['format' => 'jpg', 'quality' => 90]); } return $model; } else { return null; } } catch (\Exception $e) { } return null; }
/** * @inheritdoc */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($this->file->error === UPLOAD_ERR_OK) { // die('before2'); try { $filename = 'uploads/' . uniqid() . '.' . $this->file->extension; $this->file->saveAs($filename); // Если связанное изображение уже существует, просто изменяем его if ($file_model = $this->getImage()->one()) { } else { $file_model = new Files(); } $file_model->filename = $filename; $file_model->size = $this->file->size; $file_model->post_id = $this->id; $thumb_filename = 'uploads/thumbs/' . uniqid() . '.' . $this->file->extension; Image::thumbnail($filename, 100, 100)->save($thumb_filename, ['quality' => 90]); $file_model->thumb_filename = $thumb_filename; $file_model->save(); $this->image_id = $file_model->id; } catch (\Exception $e) { $this->addError('file', 'Ошибка загрузки файла'); return false; } } return true; } else { return false; } }
/** * Creates a new Photos model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Photos(); if ($model->load(Yii::$app->request->post())) { $model->shared_with = implode(',', $model->shared_with); $file = UploadedFile::getInstances($model, 'filename'); foreach ($file as $filename) { $model1 = new Photos(); $model1->user_id = Yii::$app->user->id; $model1->shared_with = $model->shared_with; $model1->filename = date("Ymdhis") . $filename->name; $path = Yii::getAlias('@uploads/albums/' . $model1->filename); if ($model1->save()) { $filename->saveAs($path); Image::thumbnail($path, 120, 120)->save(Yii::getAlias('@uploads/albums/thumbs/' . $model1->filename), ['quality' => 50]); } } Yii::$app->session->setFlash('success', 'Photos successfully posted.'); Yii::$app->notification->notify($model1->filename, $model1, $model1->user, Yii::$app->controller->id, $model1->shared_with); $this->redirect('index'); } else { if (Yii::$app->request->isAjax) { return $this->renderAjax('_form', ['model' => $model]); } else { return $this->render('create', ['model' => $model]); } } }
/** * Creates and caches the image thumbnail and returns full path from thumbnail file. * * @param string $filename * @param integer $width * @param integer $height * @param string $mode * @return string * @throws FileNotFoundException */ public static function thumbnailFile($filename, $width, $height, $mode = self::THUMBNAIL_OUTBOUND) { $filename = FileHelper::normalizePath(Yii::getAlias($filename)); if (!is_file($filename)) { throw new FileNotFoundException("File {$filename} doesn't exist"); } $cachePath = Yii::getAlias('@webroot/' . self::$cacheAlias); $thumbnailFileExt = strrchr($filename, '.'); $thumbnailFileName = md5($filename . $width . $height . $mode . filemtime($filename)); $thumbnailFilePath = $cachePath . DIRECTORY_SEPARATOR . substr($thumbnailFileName, 0, 2); $thumbnailFile = $thumbnailFilePath . DIRECTORY_SEPARATOR . $thumbnailFileName . $thumbnailFileExt; if (file_exists($thumbnailFile)) { if (self::$cacheExpire !== 0 && time() - filemtime($thumbnailFile) > self::$cacheExpire) { unlink($thumbnailFile); } else { return $thumbnailFile; } } if (!is_dir($thumbnailFilePath)) { mkdir($thumbnailFilePath, 0755, true); } $box = new Box($width, $height); $image = Image::getImagine()->open($filename); $image = $image->thumbnail($box, $mode); $image->save($thumbnailFile); return $thumbnailFile; }
/** * Generates a thumbnail of the image * * @param $dimension * * @return string */ public function generate($dimension) { list($width, $height) = Utils::getDimension($dimension); list($path, $basename, $extension) = $this->pathComponents(); $thumbnail = sprintf('%s/%s-%dx%d.%s', $path, $basename, $width, $height, $extension); Image::thumbnail($this->imagePath, $width, $height)->save($thumbnail); return $thumbnail; }
public function upload() { if ($this->usua_imagem instanceof \yii\web\UploadedFile) { //Image::frame($this->usua_imagem->tempName)->save(); $imagem = 'uploads/' . $this->usua_codigo . '.png'; $imagine = Image::getImagine()->open($this->usua_imagem->tempName)->thumbnail(new Box(140, 140))->save($imagem, ['quality' => 90]); } }
public static function saveThumbnail($dir, $filename, $width = 80, $height = 80) { if (trim($filename) && file_exists(Yii::getAlias($dir . '/' . $filename))) { $image = \yii\imagine\Image::thumbnail(Yii::getAlias($dir . '/' . $filename), $width, $height, ManipulatorInterface::THUMBNAIL_INSET); $image->save($dir . '/small-' . $filename); return 'small-' . $filename; } return ''; }
/** * Resizes source file to destination file according to the transformation settings, using [[Image::thumbnail()]]. * @param string $sourceFileName is the full source file system name. * @param string $destinationFileName is the full destination file system name. * @param array $transformSettings is the transform settings data, it should be the pair: 'imageWidth' and 'imageHeight', * For example: `[800, 600]` * @throws InvalidConfigException on invalid transform settings. * @return bool success. */ protected function transformImageFileResize($sourceFileName, $destinationFileName, $transformSettings) { if (!is_array($transformSettings)) { throw new InvalidConfigException('Wrong transform settings are passed to "' . get_class($this) . '::' . __FUNCTION__ . '"'); } list($width, $height) = array_values($transformSettings); Image::thumbnail($sourceFileName, $width, $height)->save($destinationFileName); return true; }
public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($insert) { $this->date_create = new Expression("NOW()"); } $d = split("\\.", $this->date); $this->date = $d[2] . '-' . $d[1] . '-' . $d[0]; $this->date_update = new Expression("NOW()"); $file = UploadedFile::getInstance($this, 'imageFile'); $dir = Yii::getAlias('@webroot/upload/images/'); if ($this->validate()) { $path = $dir . md5($file->tempName) . '.' . $file->getExtension(); $isSaved = $file->saveAs($path); if (!$isSaved) { return false; } $thumbPath = str_replace('images', 'preview', $path); $thumbWidth = Yii::$app->params['thumbWidth']; $thumbHeight = Yii::$app->params['thumbHeight']; $thumbQuality = Yii::$app->params['thumbQuality']; Image::thumbnail($path, $thumbWidth, $thumbHeight)->save($thumbPath, ['quality' => $thumbQuality]); $this->preview = str_replace(Yii::getAlias('@webroot'), '', $thumbPath); } else { return false; } return true; } return false; }