dlds/yii2-imageable
处理 AR 图像的 Yii2 扩展
0.3.1
2015-02-10 15:59 UTC
Requires
This package is not auto-updated.
Last update: 2024-09-14 17:00:59 UTC
README
此扩展旨在处理与模型关联的图像。
扩展提供用户友好的小部件,用于图像上传和删除。
功能
- 异步图像上传
- 能够生成具有不同配置的多个图像版本
- 拖放
依赖项
- Yii2
- Twitter Bootstrap 资产
- Imagine 库
安装
安装此扩展的首选方法是通过 composer。
运行以下命令之一:
php composer.phar require --prefer-dist zxbodya/yii2-image-attachment "*@dev"
或将
"zxbodya/yii2-image-attachment": "*@dev"
添加到您的 composer.json
文件的 require 部分。
用法
将 ImageAttachmentBehavior 添加到您的模型,并配置它,为上传的文件创建文件夹。
public function behaviors() { return [ TimestampBehavior::className(), 'coverBehavior' => [ 'class' => ImageAttachmentBehavior::className(), // type name for model 'type' => 'post', // image dimmentions for preview in widget 'previewHeight' => 200, 'previewWidth' => 300, // extension for images saving 'extension' => 'jpg', // path to location where to save images 'directory' => Yii::getAlias('@webroot') . '/images/post/cover', 'url' => Yii::getAlias('@web') . '/images/post/cover', // additional image versions 'versions' => [ 'small' => function ($img) { /** @var ImageInterface $img */ return $img ->copy() ->resize($img->getSize()->widen(200)); }, 'medium' => function ($img) { /** @var ImageInterface $img */ $dstSize = $img->getSize(); $maxWidth = 800; if ($dstSize->getWidth() > $maxWidth) { $dstSize = $dstSize->widen($maxWidth); } return $img ->copy() ->resize($dstSize); }, ] ] ]; }
在您的应用程序的某个位置添加 ImageAttachmentAction。在此步骤中,您还可以为此操作添加一些安全检查。
public function actions() { return [ 'imgAttachApi' => [ 'class' => ImageAttachmentAction::className(), // mappings between type names and model classes (should be the same as in behaviour) 'types' => [ 'post' => Post::className() ] ], ]; }
在您应用程序的某个位置添加 ImageAttachmentWidget,例如在编辑表单中。
echo ImageAttachmentWidget::widget( [ 'model' => $model, 'behaviorName' => 'coverBehavior', 'apiRoute' => 'test/imgAttachApi', ] )
完成!现在,您可以在应用程序的其他地方使用它
if ($model->getBehavior('coverBehavior')->hasImage()) { echo Html::img($model->getBehavior('coverBehavior')->getUrl('medium')); }