costarico / yii2-images Goto Github PK
View Code? Open in Web Editor NEWYii2-images - behavior-based module for resizing, storing, caching and attaching images.
Yii2-images - behavior-based module for resizing, storing, caching and attaching images.
// 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/*']) ?>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 создает странную ссылку в итоге ссылка несуществует
Например
/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, ], ],
обращается к дефолтным значениям, хотя и сохраняет в указанную папку
Доброй ночи.
Пытаюсь сохранить картинку.
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)>
При этом картинку сохраняет.
Если используется tablePrefix в базе данных то получаются ошибки
P.S. Пишу на руссском, автор судя по всему понимает.
Установил, настроил модуль, миграцию применил, добавил бэхавиор. Что дальше?)
Добавил fileinput[], выбираю картинку(и), сохраняю(добавляю) и ничего(
Hello,
when I call the function ImageByItemAndAlias()
the image is sent with the wrong mime type (text/html)
Can I correct this behavior?
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(), для проверки существования изображений.
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
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
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 ??
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);
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?
Для таблиц в базе данных для которых модели созданы с первичным ключом отличным от ID метод getModelSubDir не может вернуть правильное значение.
Решение проблемы в файле Module,php строка 82
$modelDir = \yii\helpers\Inflector::pluralize($modelName).'/'. $modelName . $model->getTableSchema()->primaryKey;
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?
In Details section:
$model->removeImages(); //returns array with images
should be
$model->getImages(); //returns array with images
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.
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()->...
Hi!
Can't understand why.
$image = $data->getImage();
return "<img src='{$image->getUrl()}'>";
but
$image->getPathToOrigin();
shows full path correctly.
Please, help!
Использую yii2 2.0.15.1
Подключаю как указанно, создаю field($model, 'image')->fileInput() ?>
После сохранения статьи в папках и в базе пусто... Куда копать?
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.
My model has a few images. How can I remove some of them? Not main.
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?
I am asking you as I'd like to create a clean simple code.
Thanks,
Norbert.
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
Can you change all private functions to protected so I can override them?
Приветствую
Подскажите а есть ли какое-то встроенное решение нанесения водяных знаков?
Или может как то решить можно это сторонним компонентом, может сталкивался кто то
problem, images are loaded with a delay
Here's how it happens
F5
https://www.youtube.com/watch?v=5JT76o-k2fY
preventing duplicate images would be nice.
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;
}
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
Add Yii2-user to the require section of your composer.json file:
I guess this appeared because of copy-paste?
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.
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.
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!
Hi. How can I save the original name of the picture? It`s important for SEO
Line 129 and 133 of Image model has a typo: heigth, should be height.
$newSizes['heigth'] = $size['height'];
After use method $model->removeImages() images are deleted. But directory not deleted! For example
open /behaviors/ImageBehave.php line 250 need do command delete directory.
Ошибка после обновления http://joxi.ru/12MP4yH4WnB9mJ
Calling unknown method: rico\yii2images\Module::getPrimaryKey()
I need add rule for image size. Is it possible with this module (e.g. 2 MB) ?
Подскажите, пожалуйста, как убрать плейсхолдер ? Вот если нет изображения, то и не выводить ничего. 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.
solved
Не работает миграция через композитор в 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>`
Как сделать правильно?
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'
],
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"
}
}
}
`
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:
I suggest replace any yii application dependencies with stubs(where possible).
While looking at the code I found there is some functionality of watermark. But how to use it. Can you throw some light.
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, for example "myname"? This code will show all images:
<?= Html::img($img->getUrl())?>
How to show certain?
Здравствуй.
Как вывести в виде только то изображение, у которого есть имя. У тебя в бд есть поле name, и указать я его могу вот так: $this->attachImage($path, false, myname); . А как мне получить это изображение с моим именем?
Надеюсь, я понятно пояснил...
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.