/**
  * @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'));
     }
 }
Exemple #2
1
 /**
  * @param UploadedFile $file
  */
 public function saveFile(UploadedFile $file)
 {
     if ($file) {
         $folder = \Yii::getAlias('@webroot') . '/uploads/settings/' . $this->key . '/';
         if (is_dir($folder) == false) {
             mkdir($folder, 0755, true);
         }
         $file->saveAs($folder . $file->name);
         Image::thumbnail($folder . $file->name, 160, 90)->save($folder . 'thumb_' . $file->name, ['quality' => 90]);
     }
 }
 /**
  * Creates and caches the image thumbnail and returns full path from thumbnail file.
  *
  * @param string $filename
  * @param integer $width
  * @param integer $height
  * @param string $quality
  * @return string
  * @throws FileNotFoundException
  */
 public static function thumbnailFile($filename, $width, $height, $quality = 80)
 {
     $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 . 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);
     
             $image->save($thumbnailFile);
             */
     Image::thumbnail($filename, $width, $height)->save($thumbnailFile, ['quality' => $quality]);
     return $thumbnailFile;
 }
Exemple #4
0
 /**
  * @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;
     }
 }
Exemple #5
0
 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;
     }
 }
Exemple #6
0
 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;
     }
 }
Exemple #7
0
 /**
  * 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 '';
 }
 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]);
 }
Exemple #9
0
 /**
  * @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;
     }
 }
Exemple #10
0
 /**
  *  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 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;
     }
 }
Exemple #12
0
 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];
 }
 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;
 }
 /**
  * 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]);
 }
 /**
  * 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]);
         }
     }
 }
Exemple #16
0
 /**
  * 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;
 }
Exemple #17
0
 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;
 }
 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, "裁剪成功");
 }
 /**
  * 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;
 }
 /**
  * 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 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 '';
 }
Exemple #22
0
 /**
  * createThumbImages files
  * @return mixed the uploaded image instance
  */
 public function createThumbImages($image, $imagePath, $imgOptions, $thumbPath)
 {
     $imageName = $image->name;
     $imageLink = $imagePath . $image->name;
     // Save Image Thumbs
     Image::thumbnail($imageLink, $imgOptions['small']['width'], $imgOptions['small']['height'])->save($thumbPath . "small/" . $imageName, ['quality' => $imgOptions['small']['quality']]);
     Image::thumbnail($imageLink, $imgOptions['medium']['width'], $imgOptions['medium']['height'])->save($thumbPath . "medium/" . $imageName, ['quality' => $imgOptions['medium']['quality']]);
     Image::thumbnail($imageLink, $imgOptions['large']['width'], $imgOptions['large']['height'])->save($thumbPath . "large/" . $imageName, ['quality' => $imgOptions['large']['quality']]);
     Image::thumbnail($imageLink, $imgOptions['extra']['width'], $imgOptions['extra']['height'])->save($thumbPath . "extra/" . $imageName, ['quality' => $imgOptions['extra']['quality']]);
 }
Exemple #23
0
 /**
  * @param $width
  * @param $height
  * @return string
  */
 public function getThumbnail($width, $height)
 {
     $thumb = "{$this->name}-{$width}x{$height}.{$this->extension}";
     $thumbFile = Yii::getAlias($this->module->storagePath) . '/' . $thumb;
     $thumbUrl = Yii::getAlias($this->module->storageUrl) . '/' . $thumb;
     if (file_exists($this->path) && !file_exists($thumbFile)) {
         \yii\imagine\Image::thumbnail($this->path, $width, $height, ManipulatorInterface::THUMBNAIL_INSET)->save($thumbFile, ['quality' => 60]);
     }
     return $thumbUrl;
 }
Exemple #24
0
 public function beforeSave($insert)
 {
     if ($this->fileImage != null) {
         $nameFile = time() . '_' . $this->fileImage->baseName . '.' . $this->fileImage->extension;
         // сохраняем превьюшки
         Image::thumbnail($this->fileImage->tempName, 1140, 410)->save('../web/uploads/slider/' . $nameFile, ['quality' => 90]);
         $this->src = "/uploads/slider/" . $nameFile;
     }
     return parent::beforeSave($insert);
     // TODO: Change the autogenerated stub
 }
Exemple #25
0
 public function createAvatar($uploadedAvatar)
 {
     $fileName = $this->avatar ? $this->avatar : Yii::$app->security->generateRandomString(16);
     $uploadedAvatar->saveAs(User::avatarPath() . '/' . $fileName);
     foreach (User::getAvatarSizes() as $size) {
         Image::thumbnail(User::avatarPath() . '/' . $fileName, $size[0], $size[1])->save(User::avatarPath() . "/{$fileName}_{$size[0]}_{$size[1]}.png");
     }
     Image::getImagine()->open(User::avatarPath() . '/' . $fileName)->save(User::avatarPath() . '/' . $fileName . '.png');
     unlink(User::avatarPath() . '/' . $fileName);
     $this->avatar = $fileName;
 }
Exemple #26
0
 public function createPoster($uploadedPoster)
 {
     $fileName = $this->poster ? $this->poster : Yii::$app->security->generateRandomString(16);
     $uploadedPoster->saveAs(Competition::posterPath() . '/' . $fileName);
     foreach (Competition::getPosterSizes() as $size) {
         Image::thumbnail(Competition::posterPath() . '/' . $fileName, $size[0], $size[1])->save(Competition::posterPath() . "/{$fileName}_{$size[0]}_{$size[1]}.png");
     }
     Image::getImagine()->open(Competition::posterPath() . '/' . $fileName)->save(Competition::posterPath() . '/' . $fileName . '.png');
     unlink(Competition::posterPath() . '/' . $fileName);
     $this->poster = $fileName;
 }
Exemple #27
0
 public function upload()
 {
     if ($this->imageFile && $this->validate()) {
         $filename = $this->imageFile->baseName . '.' . $this->imageFile->extension;
         $this->imageFile->saveAs('uploads/' . $filename);
         Image::thumbnail('@webroot/uploads/' . $filename, 150, 150)->save(Yii::getAlias('uploads/thumb/' . $filename), ['quality' => 100]);
         return $filename;
     } else {
         return false;
     }
 }
 public function generateThumb()
 {
     $sourcePath = $this->fileInfo->filePath;
     $thumbPath = $this->getThumbPath();
     list($thumbWidth, $thumbHeight) = $this->getThumbSizes();
     try {
         Image::thumbnail($sourcePath, $this->width, $this->height)->resize(new Box($thumbWidth, $thumbHeight))->save($thumbPath, ['quality' => FileImage::THUMB_QUALITY]);
     } catch (\Exception $e) {
         return false;
     }
     return is_readable($thumbPath);
 }
 /**
  * 保存头像
  * @return  [type] [description]
  * @version 1.0    2015-12-28T16:14:11+0800
  * @author cnzhangxl@foxmail.com
  */
 private function saveAvatar(&$model)
 {
     if ($_FILES['Manager']['tmp_name']['avatar']) {
         $rel_path = date('Ym') . '/' . date('d') . '/';
         $save_path = Yii::getAlias('@upload_path/' . $rel_path);
         !is_dir($save_path) ? mkdir($save_path, 0777, true) : null;
         $image = Image::getImagine();
         $file_name = uniqid() . '.jpg';
         Image::thumbnail($_FILES['Manager']['tmp_name']['avatar'], 160, 160)->save($save_path . $file_name);
         //$image->open($_FILES['Manager']['tmp_name']['avatar'])->save($save_path.$file_name);
         $model->avatar = $rel_path . $file_name;
     }
 }
Exemple #30
-1
 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;
 }