控制器
if($model->load(Yii::$app->request->post()))
{
//原图
$model->img = UploadedFile::getInstance($model, 'img');
$imgname=$model->img->name = time().$model->img->name;
//$model->img->saveAs('./upload/image/' . $model->img->baseName . '.' . $model->img->extension);
//设定上传目录
$path=Yii::$app->basePath.'/web/upload/image/'.$imgname;
//上传原图 图片
$model->img->saveAs($path);
//获取上传原图文件的名称
$image=$model->img;
$img=$image->name;
//echo $img;die;
//利用扩展生成缩略图
$im = null;
//取图片类型
$imagetype = strtolower($model->img->extension);
if($imagetype == 'gif')
$im = imagecreatefromgif($path);
else if ($imagetype == 'jpg')
$im = imagecreatefromjpeg($path);
else if ($imagetype == 'png')
$im = imagecreatefrompng($path);
//按时间生成新文件名
$newName=$model->img->baseName.'_thumb_'.'.'.$model->img->extension;
//设定缩略图的存放目录+名字
$thumb_path=Yii::$app->basePath.'/web/upload/image/image_thumb/'.$newName;
//生成缩略图
$sql=$model->resizeImage($im,800,450,$thumb_path,$model->img->extension);
}
在model 模型层里添加 resizeImage 方法
public static function resizeImage($im, $maxwidth, $maxheight, $name,$filetype) {
$pic_width = imagesx ( $im );
$pic_height = imagesy ( $im );
if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
if ($maxwidth && $pic_width > $maxwidth) {
$widthratio = $maxwidth / $pic_width;
$resizewidth_tag = true;
}
if ($maxheight && $pic_height > $maxheight) {
$heightratio = $maxheight / $pic_height;
$resizeheight_tag = true;
}
if ($resizewidth_tag && $resizeheight_tag) {
if ($widthratio < $heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if ($resizewidth_tag && ! $resizeheight_tag)
$ratio = $widthratio;
if ($resizeheight_tag && ! $resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if (function_exists ( "imagecopyresampled" )) {
$newim = imagecreatetruecolor ( $newwidth, $newheight );
imagecopyresampled ( $newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height );
} else {
$newim = imagecreate ( $newwidth, $newheight );
imagecopyresized ( $newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height );
}
imagejpeg ( $newim, $name );
imagedestroy ( $newim );
} else {
//$name = $name . $filetype;//这句好像多余了
imagejpeg ( $im, $name );
}
}
很简单,,这样就可以了