Yii文件(图片)上传时相关的方法

文件图片相关的方法:

1.路径:


	/**
	 * 根据优先级(新上传的缩略图->原来的缩略图->文章中第一张图片->默认图片)获取上传路径
	 * @param object $objModel WebsiteInfomation表模型对象
	 * @param object $file 用url获取的CUploadedFile的实例
	 * @return string $oldThumbPicUrl 原本保存的缩略图路径
	 *
	 */
	public function getUploadUrl( $objModel, $file, $oldThumbPicUrl=null ){
		$fileDir = 'upfile/article/thumbpic/'.date('Ymd').'/';	//设置目录名
		// 如果上传了缩略图,就使用上传的缩略图
		if( is_object( $file )&&get_class( $file ) === 'CUploadedFile' ){
			if( !is_dir( $fileDir ) ){
				if( !mkdir( $fileDir ) ){
					throw new CHttpException( 502, '目录创建失败.' );
				}
			}
			$objModel->ThumbPicUrl = '/'.$fileDir.time().'_'.rand( 0, 9999 ).'.'.$file->extensionName;   //定义文件保存的目录名称和文件名称
		// 如果没有上传缩略图,就使用文章中的第一张图片作为缩略图
		}else{
			preg_match ( "<img.*src=[\"](.*?)[\"].*?>", $objModel->Content, $match );
			// 文章中有图片,并且没有选择上传(新的)图片,则使用文章内容的第一张图片
			if ( !empty( $match ) && empty( $oldThumbPicUrl ) ){
				$objModel->ThumbPicUrl = $match[1];
			//如果文章中也没有图片,则使用默认的图片
			}else{
				if ( !$oldThumbPicUrl )	//当没有上传新的缩略图且文章中没有图片,原来的图片没有被更改掉,则不应该替换成默认图片
					$objModel->ThumbPicUrl = '/upfile/article/thumbpic/noPic.jpg';
			}
		}
	}


2.base64图片处理:

	/**
	 * 还原base64数据流图片保存到制定目录中并写入url路径
	 * @param string $xstr 内容 采集 于 content
	 * @param string $oriweb 网址 一般写null
	 * @return string
	 *
	 */
	public function replaceimg( $xstr, $oriweb ){
		$basedir = 'upfile/article/contentpic/'.date('Ymd').'/';	//设置目录名(保存路径)
		if( !is_dir( $basedir ) ){
			if( !mkdir( $basedir ) ){
				throw new CHttpException(502,'目录创建失败.');
			}
		}
		//匹配图片的src且只匹配data/base64数据流(目的是只替换base64数据流为图片url路径)
		preg_match_all( '#<img.*?src="([^"]*)"[^>]*>#i', $xstr, $match );
		foreach( $match[1] as $imgurl ){
			if ( substr( $imgurl, 0 , 10) == 'data:image' ){
				$imgurl = $imgurl;
				if(is_int(strpos($imgurl, 'http'))){
					$arcurl = $imgurl;
				} else {
					$arcurl = $oriweb.$imgurl;
				}
				$img = file_get_contents( $arcurl );
				if( !empty( $img ) ) {
					//保存图片到服务器
					$expData = explode( ';', $arcurl );
					$postfix = explode( '/', $expData[0] );
					if( strstr( $postfix[0], 'image' ) )
						$postfix = $postfix[1] == 'jpeg' ? 'jpg' : $postfix[1];	// 获取后缀名
					$fileimgname = time()."-".rand( 1000, 9999 ).".".$postfix;	// 文件名+后缀
					$filecachs=$basedir."/".$fileimgname;	//目录+文件+后缀
					$fanhuistr = file_put_contents( $filecachs, $img );	
					$saveimgfile = "/".$basedir.$fileimgname;
					$xstr=str_replace( $imgurl, $saveimgfile, $xstr );
				}
			}
		}
		//返回替换后的Content
		return $xstr;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值