<?php namespace app\m\Controller; class UploadImg extends Base { public $ext = 'png'; /** * 上传图片 * img 位二进制图片流 */ public function image_upload() { ini_set("max_execution_time", "120"); $type = input('type', 'avatar'); //上传子目录 $fileEntity = $this->parseFile(); //base64 转码 $saveDir = 'Uploads/'.$type.'/'; $time = time(); $subdir = date('Y-m-d', $time).'/'; $filename = $time.mt_rand(1000,9999); $this->validDir($saveDir.$subdir); //创建img目录 $filepath = $saveDir.$subdir.$filename.'.'.$this->ext; //图片路径 $thumbFilepath = $saveDir.$subdir.'thumb_'.$filename.'.'.$this->ext; //缩略图路径 //创建空图片文件 $ses = explode(' ', microtime()); $mis = $ses[0]*100000000; $time = time(); $res = file_put_contents(ROOT_PATH.$filepath, $fileEntity); //把转码后的base64 img 写入图片空文件 if($res) { // 图像压缩处理 $image = \think\Image::open(ROOT_PATH.$filepath); // 按照原图的比例生成一个最大为300*300的缩略图并保存为thumb.png $image->thumb(300, 300)->save(ROOT_PATH.$thumbFilepath); $path = array(); $path['ori_img'] = $filepath; $path['cut_img'] = $thumbFilepath; $this->ajaxReturn('1','上传成功',$path); }else{ $this->ajaxReturn('0','上传失败'); } } public function parseFile() { $img = $_REQUEST['img']; //post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行 $img = base64_decode(str_replace(' ','+',$img)); if(!$img) { $this->ajaxReturn('-1','params img is not valid!'); } return $img; } /* * 创建文件目录 */ public function validDir($dir) { if(!is_dir($dir)) { mkdir($dir, 0755, true); } } } ?>
php 手机站TP框架相机上传图片方法
最新推荐文章于 2022-06-12 15:52:19 发布