public function uploadFile() { $this->filename = $this->file->baseName . '.' . $this->file->extension; $this->avatar = Yii::$app->security->generateRandomString() . '.' . $this->file->extension; $this->type = $this->file->type; if ($this->validate()) { $this->save(false); $filePath = Yii::$app->params['imagePath'] . $this->avatar; $image = new ImageResize($this->file->tempName); if ($image->getSourceWidth() > 1200) { $image->resizeToWidth(1200)->save($filePath); } else { $this->file->saveAs($filePath); } return true; } return false; }
/** * @param string $repo * @param string $file * @param int $width * @param bool $archived * @param \Slim\Http\Response $response * @return mixed */ function thumb($repo, $file, $width, $archived, $response, $format) { $md5 = md5($file); $file = $md5[0] . '/' . $md5[0] . $md5[1] . '/' . $file; $path = $repo . ($archived ? 'archive/' : '') . $file; if (is_readable($path)) { $path = realpath($path); $pathParts = pathinfo($path); if (strpos($pathParts['dirname'], $repo) === 0) { $cacheDir = $repo . 'thumb/' . ($archived ? 'archive/' : '') . $file; if (!is_dir($cacheDir)) { if (!mkdir($cacheDir, 0777, true)) { return $response->withStatus(403); } } if ($format != 'jpg') { $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['basename']; } else { $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['filename'] . '.jpg'; } if (!is_readable($cacheFile)) { $image = new ImageResize($path); if ($width > $image->getSourceWidth()) { return $response->withRedirect('/images/' . $file); } else { $image->resizeToWidth($width); if ($format != 'jpg') { $image->save($cacheFile); } else { $image->save($cacheFile, IMAGETYPE_JPEG); } } } $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $cacheFile); $stream = new \GuzzleHttp\Psr7\LazyOpenStream($cacheFile, 'r'); return $response->withHeader('Content-type', $type)->withBody($stream); } } return $response->withStatus(404); }