大概的流程就是
点击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);
}
-------------------------------------------------------------下面是uniapp里面的写法
流程是选择图片,然后转为base64 然后压缩base64
图片转base64方法
getBase64Image(src) {
return new Promise(resolve => {
let xhr = new XMLHttpRequest()
xhr.open('get', src, true)
xhr.responseType = 'blob'
xhr.onload = function () {
if (this.status == 200) {
let blob = this.response
let oFileReader = new FileReader()
oFileReader.onloadend = function (e) {
const base64 = e.target.result
resolve(base64)
}
oFileReader.readAsDataURL(blob)
}
}
xhr.send()
})
},
压缩方法
compress(fileObj, callback){//fileobj 需要是blob类型
var reader = new FileReader();
reader.onload = function (e) { //要先确保图片完整获取到,这是个异步事件
var image = new Image();
image.src=e.target.result;
image.onload = function(){
let square = 0.6, //定义画布的大小,也就是图片压缩之后的像素
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 data1 = canvas.toDataURL('image/jpeg',0.6);
//压缩完成执行回调
console.log("压缩",data1)
callback(data1);
};
};
reader.readAsDataURL(fileObj);
},
base64转blob
base64toBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
调用
chooseImage(){
let that = this
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album','camera'], //从相册选择 相机拍摄
success: function (resa) {
// console.log('文件',resa.tempFilePaths[0]);
// console.log(JSON.stringify(res.tempFilePaths));
uni.showLoading({
title: '加载中'
});
that.getBase64Image(resa.tempFilePaths[0]).then(re=>{
// console.log(re)
return re
// return resa.tempFilePaths[0]
}).then(res=>{
// console.log(res)
that.compress(that.base64toBlob(res),function(e){
console.log('压缩后的',)
})
}).finally(()=>{
})
}
});
},
破罐子互摔