コード例 #1
0
ファイル: Gallery.php プロジェクト: mark38/yii2-site-mng
 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];
 }
コード例 #2
0
ファイル: ImageController.php プロジェクト: Krinnerion/shop
 /**
  * Lists all Image models.
  * @param int $id product id
  * @return mixed
  *
  * @throws NotFoundHttpException
  */
 public function actionIndex($id)
 {
     $form = new MultipleUploadForm();
     if (!Product::find()->where(['id' => $id])->exists()) {
         throw new NotFoundHttpException();
     }
     $searchModel = new ImageSearch();
     $searchModel->product_id = $id;
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     if (Yii::$app->request->isPost) {
         $form->files = UploadedFile::getInstances($form, 'files');
         if ($form->files && $form->validate()) {
             foreach ($form->files as $file) {
                 //
                 // UPLOADING THE IMAGE:
                 //
                 $image = new Image();
                 $image->product_id = $id;
                 if ($image->save()) {
                     // Save an original image;
                     $path = $image->getPath();
                     $file->saveAs($path);
                     // Original size:
                     $size = getimagesize($path);
                     $height = $size[1];
                     $width = $size[0];
                     // IMAGINE
                     ImagineImage::$driver = [ImagineImage::DRIVER_GD2];
                     $imagine = new Imagine();
                     $picture = $imagine->open($path);
                     //---------------------------
                     //                        $size = new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT);
                     //                        $center = new Center($size);
                     //---------------------------
                     //                        $picture->crop(new Point(0, 0),
                     //                            new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     /**
                      * If the image's height is bigger than needed, it must be cut.
                      * Otherwise it must be resized.
                      */
                     if ($height >= self::IMAGE_HEIGHT) {
                         $picture->thumbnail(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path, ['quality' => 100]);
                         // re-save cropped image;
                     } else {
                         $picture->resize(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     }
                     sleep(1);
                     //                        $background = new Color('#FFF');
                     //                        $topLeft    = new Point(0, 0);
                     //                        $canvas = $imagine->create(new Box(450, 450), $background);
                     //                        $canvas->paste($picture, $topLeft)->save($path);
                 }
             }
         }
     }
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'uploadForm' => $form]);
 }
コード例 #3
0
 protected function setUp()
 {
     if (!class_exists('Gmagick')) {
         $this->markTestSkipped('Skipping ImageGmagickTest, Gmagick is not installed');
     } else {
         Image::setImagine(null);
         Image::$driver = Image::DRIVER_GMAGICK;
         parent::setUp();
     }
 }
コード例 #4
0
 protected function setUp()
 {
     if (!function_exists('gd_info')) {
         $this->markTestSkipped('Skipping ImageGdTest, Gd not installed');
     } else {
         Image::setImagine(null);
         Image::$driver = Image::DRIVER_GD2;
         parent::setUp();
     }
 }
コード例 #5
0
 protected function setUp()
 {
     if (!class_exists('Imagick')) {
         $this->markTestSkipped('Skipping ImageImagickTest, Imagick is not installed');
     } elseif (defined('HHVM_VERSION')) {
         $this->markTestSkipped('Imagine does not seem to support HHVM right now.');
     } else {
         Image::setImagine(null);
         Image::$driver = Image::DRIVER_IMAGICK;
         parent::setUp();
     }
 }
コード例 #6
0
 /**
  *
  * @param \yii\web\UploadedFile $image
  * @return string
  */
 public static function saveAvatar($image)
 {
     $uploadPath = 'uploads/avatar';
     $extension = '.' . $image->extension;
     $fileName = 'avatar_' . Yii::$app->user->identity->id . '_' . time();
     $sourceFile = $uploadPath . '/' . $fileName . $extension;
     if (!file_exists($uploadPath)) {
         mkdir($uploadPath, 0777, true);
     }
     $image->saveAs($sourceFile);
     Imagine::$driver = [Imagine::DRIVER_GD2, Imagine::DRIVER_GMAGICK, Imagine::DRIVER_IMAGICK];
     $sizes = ['small' => 48, 'medium ' => 96, 'large' => 144];
     foreach ($sizes as $alias => $size) {
         $avatarUrl = "{$uploadPath}/{$fileName}-{$size}x{$size}{$extension}";
         Imagine::thumbnail($sourceFile, $size, $size)->save($avatarUrl);
         $avatars[$alias] = "/{$avatarUrl}";
         Yii::$app->user->identity->setAvatars($avatars);
     }
     return $avatars;
 }
コード例 #7
0
 protected static function generateThumbnail($file, $width, $height, $options)
 {
     $thumbName = self::getThumbFileName($file, $width, $height);
     $thumbDir = self::getThumbCachePath($thumbName);
     $thumbPath = "{$thumbDir}/{$thumbName}";
     if (file_exists($thumbPath)) {
         return $thumbPath;
     }
     FileHelper::createDirectory($thumbDir);
     $mode = ArrayHelper::getValue($options, 'mode', ManipulatorInterface::THUMBNAIL_OUTBOUND);
     $box = new Box($width, $height);
     if (isset(Yii::$app->params['imageDriver']) && is_array(Yii::$app->params['imageDriver'])) {
         Image::$driver = Yii::$app->params['imageDriver'];
     }
     $imagine = Image::getImagine();
     if ($imagine) {
         $image = $imagine->open($file);
         $image = $image->thumbnail($box, $mode);
         $image->save($thumbPath);
         return $thumbPath;
     } else {
         throw new ErrorException("Error from driver " . get_class($imagine) . " ");
     }
 }
コード例 #8
0
 /**
  * Create default thumbnail
  *
  * @param array $routes see routes in module config
  */
 public function createDefaultThumb(array $routes)
 {
     $originalFile = pathinfo($this->url);
     $dirname = $originalFile['dirname'];
     $filename = $originalFile['filename'];
     $extension = $originalFile['extension'];
     Image::$driver = [Image::DRIVER_GD2, Image::DRIVER_GMAGICK, Image::DRIVER_IMAGICK];
     $size = Module::getDefaultThumbSize();
     $width = $size[0];
     $height = $size[1];
     $thumbUrl = "{$dirname}/{$filename}-{$width}x{$height}.{$extension}";
     $basePath = Yii::getAlias($routes['basePath']);
     Image::thumbnail("{$basePath}/{$this->url}", $width, $height)->save("{$basePath}/{$thumbUrl}");
 }
コード例 #9
0
 /**
  * @expectedException \yii\base\InvalidConfigException
  */
 public function testShouldThrowExceptionOnDriverInvalidArgument()
 {
     Image::setImagine(null);
     Image::$driver = 'fake-driver';
     Image::getImagine();
 }
コード例 #10
0
 /**
  * Create default thumbnail    
  */
 public function createDefaultThumb()
 {
     $imagePath = Yii::getAlias($this->module->imagePath);
     $originalFile = pathinfo($this->filename);
     $filename = $originalFile['filename'];
     $extension = $originalFile['extension'];
     Image::$driver = [Image::DRIVER_GD2, Image::DRIVER_GMAGICK, Image::DRIVER_IMAGICK];
     $size = Module::getDefaultThumbSize();
     $width = $size[0];
     $height = $size[1];
     $thumbUrl = $imagePath . DIRECTORY_SEPARATOR . $this->dirname . DIRECTORY_SEPARATOR . "{$filename}-{$width}x{$height}.{$extension}";
     //        $thumbUrl = "$dirname/$filename-{$width}x{$height}.$extension";
     Image::thumbnail("{$imagePath}/{$this->getFilePath()}", $width, $height)->save("{$thumbUrl}");
 }
コード例 #11
0
ファイル: web.php プロジェクト: Everus/rgk_test
<?php

use yii\imagine\Image;
$params = (require __DIR__ . '/params.php');
Image::$driver = Image::DRIVER_GD2;
$config = ['id' => 'basic', 'language' => 'ru-RU', 'basePath' => dirname(__DIR__), 'defaultRoute' => 'admin/books/index', 'bootstrap' => ['log'], 'components' => ['request' => ['cookieValidationKey' => 'DE69SefCikk3tENkM5XL79dBX09nqYfP'], 'cache' => ['class' => 'yii\\caching\\FileCache'], 'user' => ['identityClass' => 'app\\models\\User', 'enableAutoLogin' => true], 'errorHandler' => ['errorAction' => 'site/error'], 'mailer' => ['class' => 'yii\\swiftmailer\\Mailer', 'useFileTransport' => true], 'formatter' => ['class' => 'yii\\i18n\\Formatter', 'dateFormat' => 'yyyy-mm-dd', 'datetimeFormat' => 'yyyy-mm-dd H:i:s', 'timeFormat' => 'H:i:s'], 'urlManager' => ['enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => ['<controller>/<action>' => '<controller>/<action>']], 'log' => ['traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [['class' => 'yii\\log\\FileTarget', 'levels' => ['error', 'warning']]]], 'db' => require __DIR__ . '/db.php'], 'params' => $params];
if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = ['class' => 'yii\\debug\\Module'];
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = ['class' => 'yii\\gii\\Module'];
}
return $config;
コード例 #12
0
ファイル: UploadImage.php プロジェクト: Kulkow/mainsite
 /**
  * @param $config
  * @param $path
  * @param $thumbPath
  */
 protected function generateImageThumb($config, $path, $thumbPath)
 {
     $width = ArrayHelper::getValue($config, 'width');
     $height = ArrayHelper::getValue($config, 'height');
     $quality = ArrayHelper::getValue($config, 'quality', 100);
     $mode = ArrayHelper::getValue($config, 'mode', ManipulatorInterface::THUMBNAIL_INSET);
     if (!$width || !$height) {
         Image::$driver = Image::DRIVER_GD2;
         $image = Image::getImagine()->open($path);
         $ratio = $image->getSize()->getWidth() / $image->getSize()->getHeight();
         if ($width) {
             $height = ceil($width / $ratio);
         } else {
             $width = ceil($height * $ratio);
         }
     }
     // Fix error "PHP GD Allowed memory size exhausted".
     ini_set('memory_limit', '512M');
     Image::thumbnail($path, $width, $height, $mode)->save($thumbPath, ['quality' => $quality]);
 }
コード例 #13
0
 /**
  * Resize image and save thumbnails.
  * If rewrite disabled and thumbnail already exists, than skip.
  *
  * @param string $filename image filename
  */
 public function resize($filename)
 {
     Image::$driver = $this->driver;
     if ($this->deleteNonActualSizes) {
         $this->deleteFiles($this->getThumbs($filename));
     }
     foreach ($this->sizes as $size) {
         $newFilename = $this->addPostfix($filename, $this->getPostfixBySize($size));
         if (!$this->enableRewrite && file_exists($newFilename)) {
             continue;
         }
         Image::thumbnail($filename, $size['width'], $size['height'], $this->mode)->save($newFilename);
     }
 }