感谢,参考了以下作者的绝大部分内容
https://blog.csdn.net/tangxiujiang/article/details/78755292
https://blog.csdn.net/u011415782/article/details/79978608
大概的流程就是
点击file选择图片
js将图片解读出base64编码,然后通过js将base64编码转为压缩后的base64
然后通过ajax或者form把压缩后的base64编码提交到服务器(php)
然后php将base64写入文件
html
<!-- 首先引入jquery!!!!!!这里没有引入 --> <img src="/Uploads/verifyinfo/cardz.png" style="width: 100%;height: 100%;">
<input id="cardz" name="cardz" class="weui-uploader__input" type="file" accept="image/*" multiple="">
<input type="hidden" id="cardzbase" name="cardzbase"> <script>
$(function(){
$("input[type=file]").on('change', function(){ var filePath = $(this).val(), //获取到input的value,里面是文件的路径
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
fileObj = document.getElementById($(this).attr('id')).files[0]; //上传文件的对象,要这样写才行,用jquery写法获取不到对象 var imgBase64str = ''; //存储图片的imgBase64
// 检查是否是图片
if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
}
var that = this;
// 调用函数,对图片进行压缩
compress(fileObj,function(imgBase64){
imgBase64str = imgBase64;//存储转换后的base64编码 var reader = new FileReader();
var img = $(that).prev("img")
file = that.files[0]
reader.addEventListener("load", function () {
img.attr("src",imgBase64str);
$("#"+$(that).attr('id')+"base").val(imgBase64str);
}, false);
reader.readAsDataURL(file)
}); })
$("#uploadcard").on("click", function(){
var cardzbase = $("#cardzbase").val();
if (cardzbase.length<=0) {
$.toast("请添加正面照");
return;
}
$.post(
"php路径",
{
cardzbase:cardzbase
},
function (data) {
alert(data.msg);
}
); });
})
// 对图片进行压缩
function compress(fileObj, callback){
if ( typeof (FileReader) === 'undefined') {
console.log("当前浏览器内核不支持base64图标压缩");
//调用上传方式不压缩
directTurnIntoBase64(fileObj,callback);
} else {
var reader = new FileReader();
reader.onload = function (e) { //要先确保图片完整获取到,这是个异步事件 var image = new Image();
image.src=e.target.result;
image.onload = function(){
square = 0.2, //定义画布的大小,也就是图片压缩之后的像素
canvas = document.createElement('canvas'), //创建canvas元素
context = canvas.getContext('2d'),
imageWidth = Math.round(square*image.width), //压缩图片的大小
imageHeight = Math.round(square*image.height),
data = ''; canvas.width = imageWidth;
canvas.height = imageHeight;
context.clearRect(0, 0, imageWidth, imageHeight); //在给定矩形内清空一个矩形
context.drawImage(this, 0, 0, imageWidth, imageHeight);
var data = canvas.toDataURL('image/jpeg',0.6);
//压缩完成执行回调 callback(data);
};
};
reader.readAsDataURL(fileObj); }
}
// 不对图片进行压缩,直接转成base64
function directTurnIntoBase64(fileObj,callback){
var r = new FileReader();
// 转成base64
r.onload = function(){
//变成字符串
imgBase64 = r.result;
//console.log(imgBase64);
callback(imgBase64);
}
r.readAsDataURL(fileObj); //转成Base64格式
}
</script>
php
<?php
/**
* [将Base64图片转换为本地图片并保存]
* @param $base64_image_content [要保存的Base64]
* @param $path [要保存的路径]
* @return bool|string
*/
public function base64_image_content($base64_image_content,$path){
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
//生成文件名
$file_name = random_str(10).".{$type}";
//路径和文件名拼接
$local_file_url = $path.$file_name;
if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
return array("filename"=>$file_name,"path"=>$path,"filepath"=>$local_file_url);
}else{
return false;
}
}else{
return false;
}
} public function uploadm()
{
$da['status'] = 0;
if (IS_POST) {
$infoz = I("post.cardzbase");
if (!$infoz || !$infof) {
// 上传错误提示错误信息
// $this->error($upload->getError());
$da['msg'] = "上传异常";
} else {
$infoz_info = $this->base64_image_content($infoz,"Uploads/verifyinfo/");
if($infof_info==false){
$da['msg'] = "上传失败";
}else{
//自己的业务...
}
}
}else{
$da['msg'] = "非法请求";
}
$this->ajaxReturn($da);
}