文件图片相关的方法:
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;
}