1. Go to this page and download the library: Download circulon/yii2-images library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
circulon / yii2-images example snippets
public function behaviors(){
return [
'image' => [
'class' => 'circlulon\images\behaviors\ImageBehavior',
'idAttribute' => 'id' // set the models id column , default : 'id'
]
];
}
public function actions(){
return [
'image' => [
'class' => 'circulon\images\actions\ImageAction',
// all the model classes to be searched by this action.
// Can be fully qualified namespace or alias
'models' => ['User', ...]
]
];
}
$model = Model::findOne(12); //Model must have id
//If an image is first it will be main image for this model
$model->attachImage('../../image.png');
//But if you need set another image as main, use second arg
$model->attachImage('../../image2.png', true);
//get all images
$images = $model->getImages();
foreach($images as $img){
//retun url to full image
echo $img->getUrl();
//return url to proportionally resized image by width
echo $img->getUrl('300x');
//return url to proportionally resized image by height
echo $img->getUrl('x300');
//return url to resized and cropped (center) image by width and height
echo $img->getUrl('200x300');
}
// get image model
$image = $model->getImage();
if($image){
//get path to resized image
echo $image->getPath('400x300');
//path to original image
$image->getPathToOrigin();
//will remove this image and all cache files
$model->removeImage($image);
// get the content of the image
$model->getContent();
}
$model->getImage(); //returns main image for model (first added image or setted as main)
$model->removeImages(); //returns array with images
//If there is no images for model, above methods will return Placeholder image or null
//If you want placeholder set up it in module configuration (see documentation)
$model->removeImage($image); //you must to pass image (object)
$model->removeImages(); //will remove all images of this model
$model->attachImage($absolutePathToImage, true); //will attach image and make it main
foreach($model->getImages() as $img){
if($img->id == $ourId){
$model->setMainImage($img);//will set current image main
}
}
$image = $model->getImage();
$sizes = $image->getSizesWhen('x500');
// the url is relative to the current controller eg /site/image/2/876293878623-x500
echo '<img width="'.$sizes['width'].'" height="'.$sizes['height'].'" src="'.$image->getUrl('x500').'" />';
// using a different controller / module+controller
// example generated url /product/image/2/876293878623-x500
echo '<img width="'.$sizes['width'].'" height="'.$sizes['height'].'" src="'.$image->getUrl('x500','product').'" />';