Yii框架实现图片上传的方法详解

2025-05-29 0 20

本文实例讲述了Yii框架实现图片上传的方法。分享给大家供大家参考,具体如下:

今天在网上看了下有关图片上传的教程,历经挫折才调试好,现在把相关代码及其说明贴出来,以供初次使用的朋友们参考。

Model:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
<?php

class Upload extends CActiveRecord {

public $image;

public static function model($className = __CLASS__) {

return $className;

}

public function tableName() {

return '{{resource}}';

}

public function rules() {

return array(

array('image', 'file', 'types'=>'jpg, gif, png')

);

}

}

注:resource为数据表,表前缀可在main.php内设置,相信朋友们在看到文件上传时应该熟悉了main.php位置在哪及运作机制。

Controller:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
<?php

class UploadController extends Controller {

public function actionIndex() {

$model=new Upload;

if(isset($_POST['Upload'])) {

$model->image=CUploadedFile::getInstance($model,'image');

$ext = $model->image->getExtensionName();

$fileName = uniqid() . '.' . $ext;

$model->image->saveAs('assets/' . $fileName);

}

$this->renderPartial('index', array('model'=>$model));

}

}

注:saveAs里面是存放图片上传后的地址,追踪下代码可以发现,该参数是move_uploaded_file函数的第二个参数,一定得是文件名。

View:

?

1

2

3

4

5
<meta charset="utf-8">

<?php echo CHtml::form(SITE_URL . 'admin/upload/index','post',array('enctype'=>'multipart/form-data')); ?>

<?php echo CHtml::activeFileField($model, 'image'); ?>

<?php echo CHtml::submitButton('提交');?>

<?php echo CHtml::endForm(); ?>

注:上面的SITE_URL为项目定义的常量,也就是项目的网址

相信经过上述步骤,朋友们应该可以上传成功图片,而且在项目下的assets目录下找到上传的图片。因为发现yii没有缩略图的方法,于是把thinkphp缩略图的方法整合了进来,把下面代码保存为Image.php放在项目下的protected/extensions目录下

?

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

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114
<?php

class Image extends CController {

/**

+----------------------------------------------------------

* 取得图像信息

*

+----------------------------------------------------------

* @static

* @access public

+----------------------------------------------------------

* @param string $image 图像文件名

+----------------------------------------------------------

* @return mixed

+----------------------------------------------------------

*/

static function getImageInfo($img) {

$imageInfo = getimagesize($img);

if ($imageInfo !== false) {

$imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));

$imageSize = filesize($img);

$info = array(

"width" => $imageInfo[0],

"height" => $imageInfo[1],

"type" => $imageType,

"size" => $imageSize,

"mime" => $imageInfo['mime']

);

return $info;

} else {

return false;

}

}

/**

+----------------------------------------------------------

* 生成缩略图

+----------------------------------------------------------

* @static

* @access public

+----------------------------------------------------------

* @param string $image 原图

* @param string $type 图像格式

* @param string $thumbname 缩略图文件名

* @param string $maxWidth 宽度

* @param string $maxHeight 高度

* @param string $position 缩略图保存目录

* @param boolean $interlace 启用隔行扫描

+----------------------------------------------------------

* @return void

+----------------------------------------------------------

*/

static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {

// 获取原图信息

$info = Image::getImageInfo($image);

if ($info !== false) {

$srcWidth = $info['width'];

$srcHeight = $info['height'];

$type = empty($type) ? $info['type'] : $type;

$type = strtolower($type);

$interlace = $interlace ? 1 : 0;

unset($info);

$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例

if ($scale >= 1) {

// 超过原图大小不再缩略

$width = $srcWidth;

$height = $srcHeight;

} else {

// 缩略图尺寸

$width = (int) ($srcWidth * $scale);

$height = (int) ($srcHeight * $scale);

}

// 载入原图

$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);

if(!function_exists($createFun)) {

return false;

}

$srcImg = $createFun($image);

//创建缩略图

if ($type != 'gif' && function_exists('imagecreatetruecolor'))

$thumbImg = imagecreatetruecolor($width, $height);

else

$thumbImg = imagecreate($width, $height);

//png和gif的透明处理 by luofei614

if('png'==$type){

imagealphablending($thumbImg, false);//取消默认的混色模式(为解决阴影为绿色的问题)

imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息(为解决阴影为绿色的问题)

}elseif('gif'==$type){

$trnprt_indx = imagecolortransparent($srcImg);

if ($trnprt_indx >= 0) {

//its transparent

$trnprt_color = imagecolorsforindex($srcImg , $trnprt_indx);

$trnprt_indx = imagecolorallocate($thumbImg, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);

imagefill($thumbImg, 0, 0, $trnprt_indx);

imagecolortransparent($thumbImg, $trnprt_indx);

}

}

// 复制图片

if (function_exists("ImageCopyResampled"))

imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);

else

imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);

// 对jpeg图形设置隔行扫描

if ('jpg' == $type || 'jpeg' == $type)

imageinterlace($thumbImg, $interlace);

// 生成图片

$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);

$imageFun($thumbImg, $thumbname);

imagedestroy($thumbImg);

imagedestroy($srcImg);

return $thumbname;

}

return false;

}

}

?>

再在项目下的protected/config/main.php中import字段加上

?

1

2

3

4

5

6
// autoloading model and component classes

'import'=>array(

'application.models.*',

'application.components.*',

'application.extensions.*', #加上此行,意思为自动载入

),

再上面的Controller加上

?

1

2

3

4

5

6

7

8

9

10

11

12
public function actionIndex() {

$model=new Upload;

if(isset($_POST['Upload'])) {

$model->image=CUploadedFile::getInstance($model,'image');

$ext = $model->image->getExtensionName();

$fileName = uniqid() . '.' . $ext;

$model->image->saveAs('assets/' . $fileName);

// 生成缩略图

Image::thumb('assets/' . $fileName, 'assets/' . uniqid() . '.' . $ext);

}

$this->renderPartial('index', array('model'=>$model));

}

这次就完整了。

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Yii框架实现图片上传的方法详解 https://www.kuaiidc.com/94986.html

相关文章

发表评论
暂无评论