public function actionIndex($name, $type) { $dir = Yii::getAlias("@webroot/{$this->dir}/_{$type}/"); if (file_exists($dir . $name)) { $this->printFile($dir . $name); } FileHelper::createDirectory($dir); $crop = 1; if (strpos($type, 'x') !== false) { list($width, $height) = explode('x', trim($type, '!^')); if (!$width || !$height || strpos($type, '^')) { $crop = 0; } elseif (strpos($type, '!')) { $crop = 2; } } else { $width = $height = $type; $crop = 0; } $fromDir = Yii::getAlias("@webroot/{$this->dir}/tmp/"); $from = $fromDir . $name; if (!file_exists($from)) { $name = 'default.jpg'; $fromDir = Yii::getAlias("@runtime/"); file_put_contents($fromDir . $name, base64_decode($this->default)); } $thumb = Image::thumbnail(Yii::getAlias($fromDir . $name), $width, $height, $crop); $thumb->save($dir . $name, ['quality' => $this->quality, 'png_compression_level' => 9]); $this->printFile($dir . $name); }
public static function add($file, $about, $owner_id, $options) { preg_match('#.\\w{1,4}$#', basename($file), $ext); $filename = preg_replace('#.\\w{1,4}$#', '', basename($file)); $newFile = Yii::getAlias('@app/../' . self::$tmpPath . '/') . strtolower(Inflector::slug($filename) . $ext[0]); if (file_exists($newFile)) { $existFile = $newFile; $newFile = str_replace(basename($existFile), uniqid() . '-' . basename($file), $existFile); } else { FileHelper::createDirectory(dirname($newFile)); } if (Image::thumbnail($file, 1920)->save($newFile, ['quality' => 100, 'png_compression_level' => 9])) { unlink($file); if (isset($existFile) && md5_file($existFile) == md5_file($newFile)) { $file = $existFile; unlink($existFile); copy($newFile, $existFile); unlink($newFile); $model = self::findOne(['name' => basename($file), 'owner_id' => $owner_id]); } else { $file = $newFile; } } list($width, $height) = getimagesize($file); $hash = md5_file($file); $name = basename($file); if (empty($model)) { $model = new self(); } if (is_string($options)) { $options = ['model' => $options]; } $model->setAttributes(compact('owner_id', 'name', 'width', 'height', 'about', 'hash') + $options); if ($model->save()) { return $model; } throw new \yii\base\Exception(print_r($model->errors, 1)); }