-
Notifications
You must be signed in to change notification settings - Fork 34
/
ImageController.php
72 lines (67 loc) · 2.1 KB
/
ImageController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
namespace mdm\upload;
use Yii;
use yii\web\NotFoundHttpException;
use yii\imagine\Image;
use yii\helpers\FileHelper;
/**
* Use to show or download uploaded file. Add configuration to your application
*
* Then you can show your file in url `Url::to(['/image', 'id' => $file_id, 'width' => 50])`
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class ImageController extends \yii\web\Controller
{
public $defaultAction = 'show';
public $savePath = '@runtime/thumbnails';
/**
* Show file
* @param integer $id
*/
public function actionShow($id, $width = null, $height = null)
{
$model = $this->findModel($id);
$response = Yii::$app->getResponse();
if ($width === null && $height === null) {
return $response->sendFile($model->filename, $model->name, [
'mimeType' => $model->type,
'fileSize' => $model->size,
'inline' => true
]);
} else {
$dir = '';
if ($width !== null) {
$dir .= 'w' . (int) $width;
}
if ($height !== null) {
$dir .= 'h' . (int) $height;
}
$filename = sprintf('%s/%s/%x/%d_%s', Yii::getAlias($this->savePath), $dir, $id % 255, $id, $model->name);
if (!file_exists($filename)) {
FileHelper::createDirectory(dirname($filename));
$image = Image::thumbnail($model->filename, $width, $height);
$image->save($filename);
}
return $response->sendFile($filename, $model->name, [
'mimeType' => $model->type,
'inline' => true
]);
}
}
/**
* Get model
* @param integer $id
* @return FileModel
* @throws NotFoundHttpException
*/
protected function findModel($id)
{
if (($model = FileModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}