BaseController.php 2.71 KB
<?php
/**
 * Created by PhpStorm.
 * User: Cibermag
 * Date: 31.08.2015
 * Time: 9:58
 */
namespace backend\components\base;

use Yii;
use yii\web\UploadedFile;
use backend\models\ImageSizerForm;
use yii\web\Controller;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use yii\imagine\Image;

class BaseController extends Controller {

    public function beforeAction($action) {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    private function resizeImg($w, $h, $imageAlias,$imageAliasSave){
        $img = Image::getImagine()->open(Yii::getAlias($imageAlias));

        $size = $img->getSize();
        $ratio = $size->getWidth()/$size->getHeight();

        $height = $h;
        $width = round($height * $ratio);


        $imagine = new Imagine();

        $imagine->open($imageAlias)
            ->resize(new Box($width, $h))
            ->save($imageAlias, array('flatten' => false));


        Image::crop($imageAlias, $w, $h,[($width/2)-($w/2),0])
            ->save(Yii::getAlias($imageAliasSave), ['quality' =>
                100]);


    }

//    private function resizeImg($w, $h, $filepath,$newfilepath){
//        list($orig_width, $orig_height) = getimagesize($filepath);
//        $width = $orig_width;
//        $height = $orig_height;
//        if($width > $height) {
//            $y = 0;
//            $x = ($width - $height) / 2;
//            $smallestSide = $height;
//        } else {
//            $x = 0;
//            $y = ($height - $width) / 2;
//            $smallestSide = $width;
//        }
//
//        $image_p = imagecreatetruecolor($w, $h);
//
//        $image = imagecreatefromjpeg($filepath);
//
//        imagecopyresampled($image_p, $image, 0, 0, $x, $y,
//            $w, $h, $smallestSide, $smallestSide);
//
//        imagejpeg($image_p, $newfilepath);
//
//
//    }

    public function actionDownloadPhoto()
    {

        $model = new ImageSizerForm();
    //die(print_r(Yii::$app->request->post()));
        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'file');

            $md5_file = md5_file($model->file->tempName);
            $imgDir = Yii::getAlias('@storage/'.$md5_file.'/');
            $imageAlias = Yii::getAlias($imgDir.$model->width.'x'.$model->height.'.'.$model->file->extension);
            $imageLink = '/storage/'.$md5_file.$model->width.'x'.$model->height.'.'.$model->file->extension;
            if(!is_dir($imgDir)) {
                mkdir($imgDir, 0755, true);
            }
            $model->file->saveAs($imageAlias);
            $this->resizeImg($model->width, $model->height, $imageAlias,$imageAlias);
            return json_encode(['link'=>$imageLink]);

        }
    }

}