Giter Club home page Giter Club logo

yii2-images's People

Contributors

akim004 avatar andku83 avatar arogachev avatar cgernert avatar cheaterby avatar colinrlly avatar costarico avatar ctolet avatar drtsb avatar evgenybukharev avatar jweil85 avatar rrhyne avatar synatree avatar vlykhoshva avatar vollossy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-images's Issues

how can i do multiple upload?

// Controller

public function actionUpdate($id)
{
$model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post())) {
        $model->image = \yii\web\UploadedFile::getInstance($model, 'image');
        if($model->image){
             foreach ($this->image as $file) {
            $path = Yii::getAlias('@webroot/uploads/').$model->file->baseName.'.'.$model->file->extension;
            $model->file->saveAs($path);
            $model->attachImage($path);
        }

        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

//view _form

field($model, 'image[]')->fileInput(['multiple' => true, 'accept' => 'uploads/*']) ?>

error 404

Hi, i made all like in the documentation, and the image is saving, but in the view i get 404 error.
Can you help me?

После обновления getUrl создает странную ссылку

После обновления getUrl создает странную ссылку в итоге ссылка несуществует
Например
/5/images/image-by-item-and-alias?item=Slider1&dirtyAlias=16a1585d57-1_2048x490.jpg

Я так понимаю первая цифра это id материала

А вот getPath работает нормально

После обновления не хочет сохранять в нужную мне папку

После отображении и кешировании игнорирует настройки указываемые в конфиге:
'modules' => [ 'yii2images' => [ 'class' => 'rico\yii2images\Module', 'imagesStorePath' => 'upload/store', 'imagesCachePath' => 'upload/cache', 'graphicsLibrary' => 'GD', 'placeHolderPath' => '@webroot/upload/files/no-image.png', 'imageCompressionQuality' => 85, ], ],
обращается к дефолтным значениям, хотя и сохраняет в указанную папку

Call to a member function setMain() on null.

Доброй ночи.

Пытаюсь сохранить картинку.

if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->img = UploadedFile::getInstance($model, 'img');
if ($model->img){
$path = Yii::getAlias('@webroot/uploads/boats/').$model->img->baseName.'.'.$model->img->extension;
$model->img->saveAs($path);
$model->attachImage($path,true);
}
return $this->redirect(['index','id'=> $model->id ]);
}

Выдает вот такую ошибку.

in D:\OpenServer\domains\kater\vendor\costa-rico\yii2-images\behaviors\ImageBehave.php at line 139
130131132133134135136137138139140141142143144145146147148
$images = $this->owner->getImages();
foreach ($images as $allImg) {

        if ($allImg->id == $img->id) {
            continue;
        } else {
            $counter++;
        }

        $allImg->setMain(false);
        $allImg->urlAlias = $this->getAliasString() . '-' . $counter;
        $allImg->save();
    }

    $this->owner->clearImagesCache();
}

/**
 * Clear all images cache (and resized copies)> 

При этом картинку сохраняет.

Table prefix bug

Если используется tablePrefix в базе данных то получаются ошибки

  1. Баг при миграции. Таблица создается без префикса
  2. Баг в модели, так же не используется префикс (models/Image.php) on line 227: return 'image'. Верно будет: return '{{%image}}

P.S. Пишу на руссском, автор судя по всему понимает.

Images send wrong MIME type

Hello,
when I call the function ImageByItemAndAlias() the image is sent with the wrong mime type (text/html)

Can I correct this behavior?

Add a way to categorize images attached to one model

Thanks for great extension!
Lets say I have a model which has 3 types of images: exteriorPic, interiorPic, customerPic
As far as I understand, it cannot be done now.
I think it would be great to have this feature (by default all the images are put to 'default' category but you can specify random string to categorize images, and then $model->getImage('exteriorPic'); would return image from the exteriorPic category.

Проверка на наличие изображения

Бывают такие случаи, когда нужно не выводить placeholder и проверять имеется ли присоединённое изображение.
Почему бы не сделать что то типа метода hasImage(), для проверки существования изображений.

Update RemoveImage

In imagebehavior, can you change this:

public function removeImage(Image $img)
    {
        $img->clearCache();

        $storePath = $this->getModule()->getStorePath();

        $fileToRemove = $storePath . DIRECTORY_SEPARATOR . $img->filePath;
        if (preg_match('@\.@', $fileToRemove) and is_file($fileToRemove)) {
            unlink($fileToRemove);
        }
        $img->delete();
    }

to this (or something better):

    public function removeImage($img)
    {
        $img = new Image;
        $img->clearCache();

        $storePath = $this->getModule()->getStorePath();

        $fileToRemove = $storePath . DIRECTORY_SEPARATOR . $img->filePath;
        if (preg_match('@\.@', $fileToRemove) and is_file($fileToRemove)) {
            unlink($fileToRemove);
        }
        $img->delete();
    }

because now it's always using your Image model, I can't override it

Functionality to get configurable names, url and path of images

Great extension and it solves most of the needs. But I need some customisation in the output. Can you please tell how to quickly achieve this.

Info: I have set store at /images/store and cache at /images/cache

  1. I want images to be named according to model properties. Say a model has properties id, product_name, supplier, manufacturer. So I want images to be named like this: "id-product_name-supplier-manufacturer".
  2. I want images to appear in this path format and url format. As simple as it can get.
    /images/store/{Model}/{Model->Id}-{Model->name}
    /images/cache/{Model}/{Model->id}-{Model->name}-{Image-size}
  3. I don't want aliases to appear in the url. By the way what exactly is that? There is no documentation of that.
  4. Plus all the images in the "images/store" and some specific sized images in the "images/cache" need to be uploaded onto AWS. Please throw some light on the best approach to do that.

intermittent error in models/Image.php ?

Hello.

I think that you make intermittent error in models/Image.php in getUrl method, in setting Url::toRoute parameters.

Maybe $this->getModule()->getPrimaryKey() must be $this->getModule()->id ??

preg_match(): No ending delimiter '/' found

When I add the first image, I get this error

 in C:\wamp\www\www.vangompelrenette.be\vendor\costa-rico\yii2-images\models\Image.php at line 64
55565758596061626364656667686970717273        ]);
    }
    */

    public function clearCache(){
        $subDir = $this->getSubDur();

        $dirToRemove = $this->getModule()->getCachePath().DIRECTORY_SEPARATOR.$subDir;

        if(preg_match('/'.preg_quote($this->modelName, '/').DIRECTORY_SEPARATOR, $dirToRemove)){
            BaseFileHelper::removeDirectory($dirToRemove);

        }

        return true;
    }

    public function getExtension(){
        $ext = pathinfo($this->getPathToOrigin(), PATHINFO_EXTENSION);

How can i run the tests?

I decided to learn more about unit-tests and yii2. So i choosed this project to work with. The instructions in the readme in the testfolder are not really working. Can someone can help me?

Error for save the model where in tables primary key not ID

Для таблиц в базе данных для которых модели созданы с первичным ключом отличным от ID метод getModelSubDir не может вернуть правильное значение.

Решение проблемы в файле Module,php строка 82

$modelDir = \yii\helpers\Inflector::pluralize($modelName).'/'. $modelName . $model->getTableSchema()->primaryKey;

eager loading

Hello! Thank you for your work.
Is there any way to use eager loading? If I call getUrl() several times on one page, there are more than 50 SQL statements being executed! It's really bad.

Can I use smth like ->with('images'), using your module?

Use With Advanced Template

I added your installation code into my files but I keep getting the error:
Calling unknown method: common\models\Sponsor::attachImage()

I'm new to yii2 and learning the way to handle things with the advanced template setup. My controller resides in backend/controllers and my model resides in common/models. I'm not sure how this setup might alter the way your module is defined in the configuration or behavior sections. Any guidance would be appreciated.

More image manipulation

I use getPath to get a resized image:
$image->getPath('300x')
But how can I use other SimpleImage functions?
$image->flip('x')->rotate(90)->best_fit(320, 200)->sepia()->...

Не сохраняет файл и не пишет в db

Использую yii2 2.0.15.1
Подключаю как указанно, создаю field($model, 'image')->fileInput() ?>
После сохранения статьи в папках и в базе пусто... Куда копать?

Setting unknown property: rico\yii2images\Module::className

Hi, i got this error by using your module from example:
'yii2images' => [
'class' => '\rico\yii2images\Module',
'imagesStorePath' => 'upload/images/store', //path to origin images
'imagesCachePath' => 'upload/images/cache', //path to resized copies
'graphicsLibrary' => 'Imagick', //but really its better to use 'Imagick'
//'placeHolderPath' => '@webroot/images/placeHolder.png', // if you want to get placeholder when image not exists, string will be processed by Yii::getAlias
//Class name to handle image storage in db
'className' => 'models/Image'
],

If i del string 'className', module works.

need help on attaching uploaded images

Hi!

As I am new to yii2 I need some help with your extension.
Can you give me an example on how to attach the uploaded images with your extension?

  1. I have a Product model and I need to attach one or more images to it.
  2. Selecting the files using the file input widget in the form
  3. What should I do after it to save the image instances with your extension?

I am asking you as I'd like to create a clean simple code.

Thanks,
Norbert.

Images do not have extensions

Hi, in order to use your extension with newerton fancybox, images must have an extension. otherwise images dont pop up properly. why is it desinged this way

Водяной знак

Приветствую
Подскажите а есть ли какое-то встроенное решение нанесения водяных знаков?
Или может как то решить можно это сторонним компонентом, может сталкивался кто то

sql error on placeholder use

Hi. When i try to use placeholder, i get an sql error binding ItemId empty string to int field in method getImage();

maybe it work on mysql, but not on Postgres. Please fix it.

if fix it with

if (empty($itemId)) {
$itemId = null;
}

Row created in image db table on every image request

Hi, I've just implemented this is my project (its awesome btw). This is a question as much as an issue..

If I call the below code 5 times, I get 5 new rows in the image table for every request, so my images table becomes huge. Should that be happening? It doesn't appear to be recreating the cached image in my cache directory though!

public static function getThumbnail($model)
{
    $imageModel = $model->getImage();

    if ($imageModel instanceof \app\models\product\Image) {

        $imageModel->attachImage($imageModel->getPath());
        $image = $imageModel->getImage();
        $imagePath = DIRECTORY_SEPARATOR . $image->getPath(self::DIMENSIONS_THUMB);

        return $imagePath;
    }
}

Cheers
Ash

Error in docs (Installation)

Add Yii2-user to the require section of your composer.json file:

I guess this appeared because of copy-paste?

Add ability to specify image model class in behavior

I think, it's not quite good for extensibility to have such strong couple in ImageBehavior:

$image = new models\Image;
$image->itemId = $this->owner->id;
$image->filePath = $pictureSubDir . '/' . $pictureFileName;
$image->modelName = $this->getModule()->getShortClass($this->owner);

So, we could specify model class in Behavior params and ask this class to implement some required interface.

sorting images

Hi!

I'm using your extension and I have one recommendation/question.

It is ok, to have a main image (for example displaying main image for product images), but what about the ordering of the other images...

Is there (or should be) a way to sort the attached images.
Probably having a sequence or other field in the db should do the trick.

Or dou you have any recommendation how to solve this thing?

Thanks,
Norbert.

$model->id

Hi!

I table the primary key is id_goods.
costa-rico/yii2-images/Module.php:82 here is an appeal to the $model->id
It gives an error message Getting unknown property: app\modules\admin\models\Products::id

sorry for bad english!

typo

Line 129 and 133 of Image model has a typo: heigth, should be height.

$newSizes['heigth'] = $size['height'];

Rule for image size

I need add rule for image size. Is it possible with this module (e.g. 2 MB) ?

Placeholder/Плейсхолдер

Подскажите, пожалуйста, как убрать плейсхолдер ? Вот если нет изображения, то и не выводить ничего. http://joxi.ru/82348wzCbpwQAO
Пробовал закомментировать вот эту строку в конфиге, но тогда плывет верстка 'placeHolderPath' => '@webroot/images/placeHolder.png',. Переопределял класс ImageBehave, закомментировав там упоминания о плейсхолдере, тоже плывет верстка. http://joxi.ru/v29DywXiPDYdmG , а элементы должны рядом стоять.
on English:
Tell me, please, how to remove placeholder? Now, if there is no picture, and then do not show anything. http://joxi.ru/82348wzCbpwQAO
I tried here to comment out this line in the config file, but then floating layout 'placeHolderPath' => '@webroot/images/placeHolder.png',. Overrides class ImageBehave, commenting there mention of the placeholder, also floats layout. http://joxi.ru/v29DywXiPDYdmG , but elements must be beside.
Sorry for my english.

Не работает миграция через композитор в yii-basic-app-2.0.8

Не работает миграция через композитор в yii-basic-app-2.0.8

`C:\xampp\htdocs\first-e-shop.local\www>yii migrate/up --migrationPath=@vendor/costa-rico/yii2-images/migrations
Yii Migration Tool (based on Yii v2.0.9)

Creating migration history table "migration"...Done.
Total 2 new migrations to be applied:
m140622_111540_create_image_table
m140622_111545_add_name_to_image_table

Apply the above migrations? (yes|no) [no]:y
*** applying m140622_111540_create_image_table
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: m140622_111540_create_image_table::pk()'

in C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\base\Component.php:285

Stack trace:
#0 C:\xampp\htdocs\first-e-shop.local\www\vendor\costa-rico\yii2-images\migrations\m140622_111540_create_image_table.php(8): yii\base\Component->_call('pk', Array)
#1 C:\xampp\htdocs\first-e-shop.local\www\vendor\costa-rico\yii2-images\migrations\m140622_111540_create_image_table.php(8): m140622_111540_create_image_table->pk()
#2 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\console\controllers\BaseMigrateController.php(509): m140622_111540_create_image_table->up()
#3 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\console\controllers\BaseMigrateController.php(130): yii\console\controllers\BaseMigrateController->migrateUp('m140622_111540
...')
#4 [internal function]: yii\console\controllers\BaseMigrateController->actionUp(0)
#5 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\base\InlineAction.php(55): call_user_func_array(Array, Array)
#6 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\base\Controller.php(154): yii\base\InlineAction->runWithParams(Array)
#7 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\console\Controller.php(119): yii\base\Controller->runAction('up', Array)
#8 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\base\Module.php(454): yii\console\Controller->runAction('up', Array)
#9 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\console\Application.php(180): yii\base\Module->runAction('migrate/up', Array)
#10 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\console\Application.php(147): yii\console\Application->runAction('migrate/up', Array)
#11 C:\xampp\htdocs\first-e-shop.local\www\vendor\yiisoft\yii2\base\Application.php(375): yii\console\Application->handleRequest(Object(yii\console\Request))
#12 C:\xampp\htdocs\first-e-shop.local\www\yii(20): yii\base\Application->run()
#13 {main}

C:\xampp\htdocs\first-e-shop.local\www>`

Как сделать правильно?

enableStrictParsing define yii2images rule

Hi,
I have in frontend config enableStrictParsing how can i define rule for yii2images module ?

something with this '/'.$this->getModule()->id.'/images/image-by-item-and-alias',
any advices ?


'urlManager' => [
            'scriptUrl'=>'/index.php',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
           'enableStrictParsing'=>true,
            'baseUrl'=>$baseUrl,
            'rules' => [
                'news'=>'news/index',
                'read/<slug:.+>'=>'news/slug'
            ],

PHP Fatal Error Class 'abeautifulsite\SimpleImage' not found

error
Class 'abeautifulsite\SimpleImage' not found
composer in the package have
tell me what to do?
`{
"name": "yiisoft/yii2-app-basic",
"description": "Yii 2 Basic Project Template",
"keywords": ["yii2", "framework", "basic", "project template"],
"homepage": "http://www.yiiframework.com/",
"type": "project",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/yii2/issues?state=open",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2"
},
"minimum-stability": "stable",
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "~2.0.5",
"yiisoft/yii2-bootstrap": "~2.0.0",
"yiisoft/yii2-swiftmailer": "~2.0.0",
"costa-rico/yii2-images": "^1.0",
"abeautifulsite/simpleimage": "^3.2"
},
"require-dev": {
"yiisoft/yii2-debug": "~2.0.0",
"yiisoft/yii2-gii": "~2.0.0",
"yiisoft/yii2-faker": "~2.0.0",

    "codeception/base": "^2.2.3",
    "codeception/verify": "~0.3.1",
    "codeception/specify": "~0.4.3"
},
"config": {
    "process-timeout": 1800
},
"scripts": {
    "post-create-project-cmd": [
        "yii\\composer\\Installer::postCreateProject"
    ]
},
"extra": {
    "yii\\composer\\Installer::postCreateProject": {
        "setPermission": [
            {
                "runtime": "0777",
                "web/assets": "0777",
                "yii": "0755"
            }
        ],
        "generateCookieValidationKey": [
            "config/web.php"
        ]
    },
    "asset-installer-paths": {
        "npm-asset-library": "vendor/npm",
        "bower-asset-library": "vendor/bower"
    }
}

}
`

Standalone unit tests

As I understood, at this moment tests relies on application that should be pre-deployed. I think it's not quite good idea because of such reasons:

  • Needs an additional work to be done(deploy application)
  • Dependent on application config

I suggest replace any yii application dependencies with stubs(where possible).

How to use watermark

While looking at the code I found there is some functionality of watermark. But how to use it. Can you throw some light.

Site may be attacked by several requests for generate huge images (DDOS)

Let's say i have gallery with high-resolution images in my site.
I'm using this extension and urls to images would be:
/yii2images/images/image-by-item-and-alias.html?item=Gallery&dirtyAlias=1234451233-1.jpg

Original image has big resolution and big size (more than 3Mb).
If someone try open url like this /yii2images/images/image-by-item-and-alias.html?item=Gallery&dirtyAlias=1234451233-1_10000.jpg server will generate image with 10000px width. This operation is very heavy for server.
Attacker can send several request for generating numerous images:
/yii2images/...1234451233-1_10001.jpg
/yii2images/....1234451233-1_10002.jpg
...
/yii2images/....1234451233-1_19001.jpg
/yii2images/...1234451233-1_19002.jpg

In this case extension can't using cache for images and your server will generate more than 10000 images or will be crashed.
Also free space on your hdd will quickly ending (image with 10000px width is very huge).

So approach for generating images must be reworked.

How to display in "view" of images, which have a name?

How to display in "view" of images, which have a name, for example "myname"? This code will show all images:
<?= Html::img($img->getUrl())?>
How to show certain?

Здравствуй.
Как вывести в виде только то изображение, у которого есть имя. У тебя в бд есть поле name, и указать я его могу вот так: $this->attachImage($path, false, myname); . А как мне получить это изображение с моим именем?
Надеюсь, я понятно пояснил...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.