前台代码
document.getElementById('head-image').addEventListener('tap', function() {
if (mui.os.plus) {
var a = [{
title: "拍照"
}, {
title: "从手机相册选择"
}];
plus.nativeUI.actionSheet({
title: "修改用户头像",
cancel: "取消",
buttons: a
}, function(b) { /*actionSheet 按钮点击事件*/
switch (b.index) {
case 0:
break;
case 1:
getImage1(); /*拍照*/
break;
case 2:
galleryImg1();/*打开相册*/
break;
default:
break;
}
})
}
}, false);
//拍照上传
function getImage1() {
var c = plus.camera.getCamera();
c.captureImage(function(e) {
plus.io.resolveLocalFileSystemURL(e, function(entry) {
var s = entry.toLocalURL() + "?version=" + new Date().getTime();
uploadHead1(s); /*上传图片*/
}, function(e) {
console.log("读取拍照文件错误:" + e.message);
});
}, function(s) {
console.log("error" + s);
}, {
filename: "_doc/head.png"
})
}
//从相册选图上传
function galleryImg1() {
plus.gallery.pick(function(a) {
plus.io.resolveLocalFileSystemURL(a, function(entry) {
plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
root.getFile("head.png", {}, function(file) {
//文件已存在
file.remove(function() {
console.log("file remove success");
entry.copyTo(root, 'head.png', function(e) {
var e = e.fullPath + "?version=" + new Date().getTime();
uploadHead1(e); /*上传图片*/
//变更大图预览的src
//目前仅有一张图片,暂时如此处理,后续需要通过标准组件实现
},
function(e) {
console.log('copy image fail:' + e.message);
});
}, function() {
console.log("delete image fail:" + e.message);
});
}, function() {
//文件不存在
entry.copyTo(root, 'head.png', function(e) {
var path = e.fullPath + "?version=" + new Date().getTime();
uploadHead1(path); /*上传图片*/
},
function(e) {
console.log('copy image fail:' + e.message);
});
});
}, function(e) {
console.log("get _www folder fail");
})
}, function(e) {
console.log("读取拍照文件错误:" + e.message);
});
}, function(a) {}, {
filter: "image"
})
};
//上传
function uploadHead1(imgPath) {
var wa = plus.nativeUI.showWaiting(); //加载提示图
var mainImage= document.getElementById('head-image'); //图片元素
mainImage.src = imgPath;
var image = new Image();
image.src = imgPath;
image.onload = function() {
var imgData = getBase64Image(image); //图片压缩
/*在这里调用上传接口*/
/*直接base64位上传*/
// mui.ajax(ROOTURL+'/index.php?Mobile=PhoneUploadController', {
// data: {
// Old_img:Old_img,
// upLoadPath : upLoadPath ,
// Img_prefix:'AD_' ,
// isTransform: 1 ,
// tWidth:300 ,
// tHeight: 300
// },
// dataType: 'json',
// type: 'post',
// timeout: 10000,
// success: function(data) {
// console.log(JSON.stringify(data));
// console.log('上传成功');
// },
// error: function(xhr, type, errorThrown) {
// mui.toast('网络异常,请稍后再试!');
// }
// });
/*mui 上传插件上传*/
//初始化上传任务 (已文件方式上传) 参数一后台处理文件地址 参数二 回调函数
var task = plus.uploader.createUpload(ROOTURL+'/index.php?Mobile=PhoneUploadController', {
method: "POST" ,
timeout: 300, //上传任务超时时间
retry: 1 //上传任务重试次数,默认为3次
},
function(t, status) {
if (status == 200) {
console.log("上传成功");
console.log(t)
console.log(JSON.stringify(JSON.parse(t.responseText)));
} else {
console.log("上传失败"+t+ROOTURL+'index.php?Mobile=PhoneUploadController');
}
wa.close();
}
);
task.addFile(imgPath,{key:"head"}); //增加上传图 第一个参数为图片地址 第二个参数为图片标记 自己填
task.addData("Old_img",Old_img); //增加自定义post传参
task.addData("upLoadPath",upLoadPath); //
task.addData("Img_prefix",user_info[0]['Id']+'_'+getnowtime());
task.addData("isTransform",'1');
task.addData("tWidth",'215');
task.addData("tWidth",'215');
task.start();
}
}
//将图片压缩转成base64
function getBase64Image(img) {
var canvas = document.createElement("canvas");
var width = img.width;
var height = img.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > 100) {
height = Math.round(height *= 100 / width);
width = 100;
}
} else {
if (height > 100) {
width = Math.round(width *= 100 / height);
height = 100;
}
}
canvas.width = width; /*设置新的图片的宽度*/
canvas.height = height; /*设置新的图片的长度*/
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height); /*绘图*/
var dataURL = canvas.toDataURL("image/png", 0.8);
console.log(dataURL);
return dataURL.replace("data:image/png;base64,", "");
}
后台处理文件代码PHP代码
<?php
/*
* 作者 沃航科技 李强
* 时间 2017年4月24日18:44:55
* 作用 图片上传
* 下面参数均为POST提交
* 参数1 Old_img : 原图片全地址
* 参数2 upLoadPath : 图片存放地址 必填 比如 '/Plugins/img/AD_img/'
* 参数3 Img_prefix : 图片名称前缀 默认空
* 参数4 isTransform : 是否变换图片 默认 0
*
* 提示 下面的参数为可选参数当选择变换图片后请输入以下参数
* 提示 如果变换后图片路径以及图片名等于变换前的图片路径及图片名(也就是不传递参数tPath 和 tImg_prefix)
则会默认变换后的替换变换前的图
*
* 参数5 isCut : 是否裁剪图片 默认 1(裁剪)
* 参数6 tWidth : 变换后的图片宽度 默认 200
* 参数7 tHeight : 变换后图片的高度 默认 100
* 参数8 tPath : 变换后图片存放路径 默认 等于upLoadPath
* 参数9 tImg_prefix : 变换后文件名前缀 默认 等于Img_prefix
*/
// header("Access-Control-Allow-Origin:*"); //允许跨域访问。
// // 响应类型
// header('Access-Control-Allow-Methods:POST');
// // 响应头设置
// header('Access-Control-Allow-Headers:x-requested-with,content-type');
ini_set("error_reporting","E_ALL & ~E_NOTICE");
$upLoadPath = $_POST['upLoadPath'];
$Img_prefix = '';
if(isset($_POST['Img_prefix']))
{
$Img_prefix = $_POST['Img_prefix'];
}
$isTransform = 0;
$isCut = 1 ;
$tWidth = 200;
$tHeight = 100;
$tPath = $upLoadPath;
$tImg_prefix = $Img_prefix;
if(isset($_POST['isTransform']) )
{
$isTransform = 1;
if(isset($_POST['isCut']))
{
$isCut = $_POST['isCut'];
}
if(isset($_POST['tWidth']))
{
$tWidth = $_POST['tWidth'];
}
if(isset($_POST['tHeight']))
{
$tHeight = $_POST['tHeight'];
}
if(isset($_POST['tPath']))
{
$tPath = $_POST['tPath'];
}
if(isset($_POST['tImg_prefix']))
{
$tImg_prefix = $_POST['tImg_prefix'];
}
}
$file_infor = var_export($_FILES,true);
//echo $file_infor;
$files = array();
$success = 0; //用户统计有多少张图片上传成功了
foreach ($_FILES as $item) {
$index = count($files);
$files[$index]['srcName'] = $item['name']; //上传图片的原名字
$files[$index]['error'] = $item['error']; //和该文件上传相关的错误代码
$files[$index]['size'] = $item['size']; //已上传文件的大小,单位为字节
$files[$index]['type'] = $item['type']; //文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"
$files[$index]['success'] = false; //这个用于标志该图片是否上传成功
$files[$index]['path'] = ''; //存图片路径
// 接收过程有没有错误
if($item['error'] != 0) continue;
//判断图片能不能上传
if(!is_uploaded_file($item['tmp_name'])) {
$files[$index]['error'] = 8000;
continue;
}
//扩展名
$extension = '';
if(strcmp($item['type'], 'image/jpeg') == 0) {
$extension = '.jpg';
}
else if(strcmp($item['type'], 'image/png') == 0) {
$extension = '.png';
}
else if(strcmp($item['type'], 'image/gif') == 0) {
$extension = '.gif';
}
else {
//如果type不是以上三者,我们就从图片原名称里面去截取判断去取得(处于严谨性)
$substr = strrchr($item['name'], '.');
if(FALSE == $substr) {
$files[$index]['error'] = 8002;
continue;
}
//取得元名字的扩展名后,再通过扩展名去给type赋上对应的值
if(strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0 ) {
$files[$index]['type'] = 'image/jpeg';
}
else if(strcasecmp($substr, '.png') == 0) {
$files[$index]['type'] = 'image/png';
}
else if(strcasecmp($substr, '.gif') == 0) {
$files[$index]['type'] = 'image/gif';
}
else {
$files[$index]['error'] = 8003;
continue;
}
$extension = $substr;
}
//对临时文件名加密,用于后面生成复杂的新文件名
$md5 = md5_file($item['tmp_name']);
//取得图片的大小
$imageInfo = getimagesize($item['tmp_name']);
$rawImageWidth = $imageInfo[0];
$rawImageHeight = $imageInfo[1];
//设置图片上传路径,放在upload文件夹,以年月日生成文件夹分类存储,
//rtrim(base_url(), '/')其实就是网站的根目录,大家自己处理
//$path = rtrim(base_url(), '/') . '/upload/' . date('Ymd') . '/';
$path = '.'.$upLoadPath; //返回路径
$serverPath = $_SERVER["DOCUMENT_ROOT"].$upLoadPath;//保存路径
//.'/Worldflying_php/Plugins/img/AD_img';
//确保目录可写
ensure_writable_dir($path);
//文件名
//$name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
// $item['name']=iconv("UTF-8","gb2312", $item['name']);
$name = $Img_prefix.$item['name'];
//加入图片文件没变化到,也就是存在,就不必重复上传了,不存在则上传
$ret = file_exists($path . $name) ? true : move_uploaded_file($item['tmp_name'], $serverPath . $name);
if($ret === false) {
//$Old_img = $_SERVER["DOCUMENT_ROOT"].'/Worldflying_php/'.$upLoadPath.$_POST['Img_prefix'].$_POST['Old_img'];
if(file_exists($_POST['Old_img']))
{
unlink($_POST['Old_img']);
}
$files[$index]['error'] = 8004;
continue;
}
else {
$files[$index]['path'] = $path . $name; //存图片路径
$files[$index]['success'] = true; //图片上传成功标志
$files[$index]['width'] = $rawImageWidth; //图片宽度
$files[$index]['height'] = $rawImageHeight; //图片高度
$success ++; //成功+1
//$Old_img = $_SERVER["DOCUMENT_ROOT"].'/Worldflying_php/'.$upLoadPath.$_POST['Img_prefix'].$_POST['Old_img'];
//unlink($_POST['Old_img']);
if(file_exists($_POST['Old_img']))
{
unlink($_POST['Old_img']);
}
$filename=$path.$name;
if($isTransform == 1)
{
$resizeimage=new ResizeImage($filename, $tWidth, $tHeight, $isCut, '.'.$tPath.$tImg_prefix.$item['name']);
$files[$index]['tpath'] = '.'.$tPath.$tImg_prefix.$item['name'] ; //存图片路径
$files[$index]['tsuccess'] = true; //图片上传成功标志
}
}
}
//将图片已json形式返回给js处理页面 ,这里大家可以改成自己的json返回处理代码
echo json_encode(array(
'total' =>count($files),
'success' =>$success,
'files' =>$files,
'serverPath' =>$serverPath,
));
/*********************************分割*************************************************/
//这里我附上ensure_writable_dir()函数的代码
/**
* 确保文件夹存在并可写
*
* @param string $dir
*/
function ensure_writable_dir($dir) {
if(!file_exists($dir)) {
mkdir($dir, 0766, true);
chmod($dir, 0766);
chmod($dir, 0777);
}
else if(!is_writable($dir)) {
chmod($dir, 0766);
chmod($dir, 0777);
if(!is_writable($dir)) {
throw new FileSystemException("目录 $dir 不可写");
}
}
}
?>
后台图片压缩
<?php
ini_set("error_reporting","E_ALL & ~E_NOTICE");
/**
* 功能:php生成缩略图片的类
* 构造函数及调用方法 $resizeimage=new ResizeImage($img,$wid,$hei,$c,$dstpath,$quality=100);
* 参数一 : 文件地址 带文件名
* 参数二 : 变换后宽度
* 参数三 : 变换后高度
* 参数四 : 是否裁剪图片
* 参数五 : 变换后存放地址带文件名
*/
class ResizeImage{
public $type;//图片类型
public $width;//实际宽度
public $height;//实际高度
public $resize_width;//改变后的宽度
public $resize_height;//改变后的高度
public $cut;//是否裁图
public $srcimg;//源图象
public $dstimg;//目标图象地址
public $im;//临时创建的图象
public $quality;//图片质量
public $img_func;
function __construct($img,$wid,$hei,$c,$dstpath,$quality=100){
$this->srcimg=$img;
$this->resize_width=$wid;
$this->resize_height=$hei;
$this->cut=$c;
$this->quality=$quality;
$this->type=strtolower(substr(strrchr($this->srcimg,'.'),1));//图片的类型
$this->initi_img();//初始化图象
$this->dst_img($dstpath);//目标图象地址
@$this->width=imagesx($this->im);
@$this->height=imagesy($this->im);
$this->newimg();//生成图象
@ImageDestroy($this->im);
}
function newimg(){
$resize_ratio=($this->resize_width)/($this->resize_height);//改变后的图象的比例
@$ratio=($this->width)/($this->height);//实际图象的比例
if(($this->cut)=='1'){//裁图
if($img_func==='imagepng'&&(str_replace('.','',PHP_VERSION)>=512)){ //针对php版本大于5.12参数变化后的处理情况
$quality=9;
}
if($ratio>=$resize_ratio){//高度优先
$newimg=imagecreatetruecolor($this->resize_width,$this->resize_height);
imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,(($this->height)*$resize_ratio),$this->height);
imagejpeg($newimg,$this->dstimg,$this->quality);
}
if($ratio<$resize_ratio){//宽度优先
$newimg=imagecreatetruecolor($this->resize_width,$this->resize_height);
imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,$this->resize_height,$this->width,(($this->width)/$resize_ratio));
imagejpeg($newimg,$this->dstimg,$this->quality);
}
}else{//不裁图
if($ratio>=$resize_ratio){
$newimg=imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio);
imagecopyresampled($newimg,$this->im,0,0,0,0,$this->resize_width,($this->resize_width)/$ratio,$this->width,$this->height);
imagejpeg($newimg,$this->dstimg,$this->quality);
}
if($ratio<$resize_ratio){
@$newimg=imagecreatetruecolor(($this->resize_height)*$ratio,$this->resize_height);
@imagecopyresampled($newimg,$this->im,0,0,0,0,($this->resize_height)*$ratio,$this->resize_height,$this->width,$this->height);
@imagejpeg($newimg,$this->dstimg,$this->quality);
}
}
}
function initi_img(){//初始化图象
if($this->type=='jpg' || $this->type=='jpeg'){
$this->im=imagecreatefromjpeg($this->srcimg);
}
if($this->type=='gif'){
$this->im=imagecreatefromgif($this->srcimg);
}
if($this->type=='png'){
$this->im=imagecreatefrompng($this->srcimg);
}
if($this->type=='wbm'){
@$this->im=imagecreatefromwbmp($this->srcimg);
}
if($this->type=='bmp'){
$this->im=$this->ImageCreateFromBMP($this->srcimg);
}
}
function dst_img($dstpath){//图象目标地址
$full_length=strlen($this->srcimg);
$type_length=strlen($this->type);
$name_length=$full_length-$type_length;
$name=substr($this->srcimg,0,$name_length-1);
$this->dstimg=$dstpath;
//echo $this->dstimg;
}
function ImageCreateFromBMP($filename){ //自定义函数处理bmp图片
if(!$f1=fopen($filename,"rb"))returnFALSE;
$FILE=unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset",fread($f1,14));
if($FILE['file_type']!=19778)returnFALSE;
$BMP=unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
'/Vvert_resolution/Vcolors_used/Vcolors_important',fread($f1,40));
$BMP['colors']=pow(2,$BMP['bits_per_pixel']);
if($BMP['size_bitmap']==0)$BMP['size_bitmap']=$FILE['file_size']-$FILE['bitmap_offset'];
$BMP['bytes_per_pixel']=$BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2']=ceil($BMP['bytes_per_pixel']);
$BMP['decal']=($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal']-=floor($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal']=4-(4*$BMP['decal']);
if($BMP['decal']==4)$BMP['decal']=0;
$PALETTE=array();
if($BMP['colors']<16777216)
{
$PALETTE=unpack('V'.$BMP['colors'],fread($f1,$BMP['colors']*4));
}
$IMG=fread($f1,$BMP['size_bitmap']);
$VIDE=chr(0);
$res=imagecreatetruecolor($BMP['width'],$BMP['height']);
$P=0;
$Y=$BMP['height']-1;
while($Y>=0)
{
$X=0;
while($X<$BMP['width'])
{
if($BMP['bits_per_pixel']==24)
$COLOR=unpack("V",substr($IMG,$P,3).$VIDE);
elseif($BMP['bits_per_pixel']==16)
{
$COLOR=unpack("n",substr($IMG,$P,2));
$COLOR[1]=$PALETTE[$COLOR[1]+1];
}
elseif($BMP['bits_per_pixel']==8)
{
$COLOR=unpack("n",$VIDE.substr($IMG,$P,1));
$COLOR[1]=$PALETTE[$COLOR[1]+1];
}
elseif($BMP['bits_per_pixel']==4)
{
$COLOR=unpack("n",$VIDE.substr($IMG,floor($P),1));
if(($P*2)%2==0)$COLOR[1]=($COLOR[1]>>4);else$COLOR[1]=($COLOR[1]&0x0F);
$COLOR[1]=$PALETTE[$COLOR[1]+1];
}
elseif($BMP['bits_per_pixel']==1)
{
$COLOR=unpack("n",$VIDE.substr($IMG,floor($P),1));
if(($P*8)%8==0)$COLOR[1]=$COLOR[1]>>7;
elseif(($P*8)%8==1)$COLOR[1]=($COLOR[1]&0x40)>>6;
elseif(($P*8)%8==2)$COLOR[1]=($COLOR[1]&0x20)>>5;
elseif(($P*8)%8==3)$COLOR[1]=($COLOR[1]&0x10)>>4;
elseif(($P*8)%8==4)$COLOR[1]=($COLOR[1]&0x8)>>3;
elseif(($P*8)%8==5)$COLOR[1]=($COLOR[1]&0x4)>>2;
elseif(($P*8)%8==6)$COLOR[1]=($COLOR[1]&0x2)>>1;
elseif(($P*8)%8==7)$COLOR[1]=($COLOR[1]&0x1);
$COLOR[1]=$PALETTE[$COLOR[1]+1];
}
else
returnFALSE;
imagesetpixel($res,$X,$Y,$COLOR[1]);
$X++;
$P+=$BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
fclose($f1);
return$res;
}
}
?>
以上代码参考网上同类代码 自己做了修改