前段日子中涉及到了在移動端圖片壓縮上傳反轉的問題;
PC端沒有問題,PC處理本身會比移動端快;
1.遇到了問題拍照H5瀏覽器的不兼容 input file ;
2.圖片旋轉的問題,旋轉你就要處理,但是canvas旋轉的過程中,我已經儘量釋放了內存,雖然JAVASCRIPT本身自帶緩存機制;
3.通過攝像機拍的照片一定要/3 /2 圖片高寬減少3倍 或者兩倍,另外定一個最小值;這樣避免瀏覽器崩潰,不然呵呵呵呵呵呵呵;
4.最後IOS系統4s手機的不支持,最後換回了原生開發;
var attrbaifenbi = '';
function tokenfng(fn) {
var token = ''
if(getUrlParamtoken('token')!=null)
{
token = getUrlParamtoken('token');
}else
{
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
token = nativetoken();
console.log(token+'我是客戶端返回的token')
localStorage.setItem('apptoken',token);
} else {
if (/(Android)/i.test(navigator.userAgent)) {
token = Android.nativetoken()
}
}
}
fn(token)
}
function uptoken(token, fn) {
$.getJSON(config_apiurl + 'identify/upload', {token: token}, function (uptoken) {
if (uptoken.code == '200') {
fn(uptoken)
} else {
alert('獲取上傳UPTOEKN錯誤,請稍後再試')
}
});
}
function getBlob(buffer, format) {
var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder;
if (Builder) {
var builder = new Builder;
builder.append(buffer);
return builder.getBlob(format);
} else {
return new window.Blob([buffer], {type: format});
}
}
var Qiniu_upload = function (f, type, token, key, fn1, fn2) {
var xhr = new XMLHttpRequest();
var text = window.atob(f.split(",")[1]);
var buffer = new Uint8Array(text.length);
var pecent = 0, loop = null;
for (var i = 0; i < text.length; i++) {
buffer[i] = text.charCodeAt(i);
}
var blob = getBlob(buffer, type);
var Qiniu_UploadUrl = "http://up.qiniu.com";
// alert('請求中')
xhr.open('POST', Qiniu_UploadUrl, true);
// alert('請求結束')
var formData, startDate;
formData = new FormData();
formData.append('key', key);
// formData.append('x:skuno', skuno);
formData.append('token', token);
formData.append('file', blob);
// console.log(formData)
xhr.onreadystatechange = function (response) {
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
// alert('上傳成功')
console.log(response.target.response)
var datas = JSON.parse(response.target.response);
fn1(datas)
return 'success';
} else if (xhr.status != 200 && xhr.responseText) {
alert('圖片上傳失敗請稍後再試')
console.log(xhr)
console.log(response)
return false;
// return 'failure';
}
};
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
fn2(complete)
}
};
console.log(formData)
xhr.send(formData);
};
newhtml();
$('.changetoolos').on('click',function () {
alert('請等待圖片上傳成功後再選則')
});
function newhtml() {
tokenfng(function (token) {
$.getJSON(config_apiurl + 'identify/show', {token: token}, function (data) {
$.hideLoading();
console.log(data)
// 優化寫法
function democallback() {
uptoken(token,function (uptoken) {
var idexifup = $('.openimg #upload')
var nneweach = $.each(idexifup,function (e,v) {
idexifup.eq(e).bind('change').on('change',function () {
$(' body .changetoolos').show();
// //圖片信息
var chernder = $('body .openimg').eq(e);
chernder.children('.zhezhaosen').remove();
var apppendo = '<div class="zhezhaosen"><div class="mt25 txt13">圖片上傳中<br>0%</div></div>';
$(' body .openimg').eq(e).append(apppendo)
var that = this;
var myimgfont = $(this)[0].files[0];
var urlfunck = window.URL.createObjectURL($(this)[0].files[0]);
console.log(urlfunck)
// console.log($(this)[0])
// $('.openimg .yindaoshangchuan').eq(e).css('background-image', "url(" + urlfunck + ")");
//上傳憑證
var uptokendata = uptoken.uptoken;
//當前時間
var prekey = uptoken.pre_key;
var imgname = myimgfont.name.split('.')[0]
console.log(imgname+'名稱')
var key = prekey + imgname +Date.parse(new Date()) / 1000;
var type = myimgfont.type;
// chernder.children('.zhezhaosen').remove();
// $('.openimg .yindaoshangchuan').eq(e).css('background-image', "url('http://test.wwcdn.cn/ww')")
// alert(imgname)
selectFileImage($(this),function (base64) {
// con
$('.openimg .yindaoshangchuan').eq(e).css('background-image', "url(" + base64 + ")");
$(' body .changetoolos').hide();
//
// Qiniu_upload(base64, type, uptoken.uptoken, key, function (updata) {
//
//// $('body .zhezhaosen').eq(e).remove();
// chernder.children('.zhezhaosen').remove();
//
//
// var okbaifen = '<div class="zhezhaosen"><div class="mt25 txt13">圖片上傳成功<br>100%</div></div>';
// $(' body .openimg').eq(e).append(okbaifen)
//
// $(that).attr('data-imgname', updata.key);
//
//
// }, function (callbaifenbi) {
//
// chernder.children('.zhezhaosen').remove();
// var textsend = '<div class="zhezhaosen"><div class="mt25 txt13">圖片上傳中<br>' + (callbaifenbi - 1) + '%</div></div>';
// $(' body .openimg').eq(e).append(textsend)
//
// });
})
})
nneweach = null;
});
$('.fortotop').on('click', function () {
var id_name = $('#xingming').val();
var id_number = $('#shenfnezheng').val();
var dataimg = $('.openimg #upload')
var front = $('body .a').attr('data-imgname');
var back = $('body .b').attr('data-imgname');
var inhand = $('body .c').attr('data-imgname');
var zhengze = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;
if (id_name != null && id_number != null && front !== null && back != null && inhand != null) {
if (zhengze.test(id_number) != true) {
alert('身份證填寫錯誤,修改後再提交')
return
} else {
$.post(config_apiurl + 'identify/create',
{
token: token,
id_name: id_name,
id_number: id_number,
front: front,
back: back,
inhand: inhand
}, function (message) {
console.log(message)
var data = JSON.parse(message)
console.log(data)
console.log(localStorage.getItem('apptoken')+'條連接的token')
if(data.code =='200')
{
alert('提交成功')
// newhtml();
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
var tokenurl = localStorage.getItem('apptoken');
setTimeout(function () {
window.location = config_url+'app/realname.html?token='+ tokenurl;
},1000)
} else {
if (/(Android)/i.test(navigator.userAgent)) {
window.location = window.location.href;
}
}
}else
{
alert(data.message)
}
})
}
} else {
alert('請填寫正確的認證資料')
}
});
});
};
function selectFileImage(fileObj,fn1) {
var file = fileObj[0].files[0];
//圖片方向角 added by lzk
var Orientation = null;
if (file) {
console.log("正在上傳,請稍後...");
var rFilter = /^(image\/jpeg|image\/png)$/i; // 檢查圖片格式
if (!rFilter.test(file.type)) {
//showMyTips("請選擇jpeg、png格式的圖片", false);
return;
}
// var URL = URL || webkitURL;
//獲取照片方向角屬性,用戶旋轉控制
EXIF.getData(file, function() {
// alert(EXIF.pretty(this));
EXIF.getAllTags(this);
//alert(EXIF.getTag(this, 'Orientation'));
Orientation = EXIF.getTag(this, 'Orientation');
//return;
});
var oReader = new FileReader();
oReader.onload = function(e) {
//var blob = URL.createObjectURL(file);
//_compress(blob, file, basePath);
var image = new Image();
image.src = e.target.result;
image.onload = function() {
var expectWidth = this.naturalWidth/3;
var expectHeight = this.naturalHeight/3;
if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
expectWidth = 800;
expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
} else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
expectHeight = 1200;
expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
}
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = expectWidth;
canvas.height = expectHeight;
console.log(canvas.width)
console.log(canvas.height)
ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
var base64 = null;
//修復ios
if (navigator.userAgent.match(/iphone/i)) {
console.log('iphone');
//alert(expectWidth + ',' + expectHeight);
//如果方向角不爲1,都需要進行旋轉 added by lzk
if(Orientation != "" && Orientation != 1){
// alert('旋轉處理');
switch(Orientation){
case 6://需要順時針(向左)90度旋轉
// alert('需要順時針(向左)90度旋轉');
rotateImg(this,'left',canvas);
break;
case 8://需要逆時針(向右)90度旋轉
// alert('需要順時針(向右)90度旋轉');
rotateImg(this,'right',canvas);
break;
case 3://需要180度旋轉
// alert('需要180度旋轉');
rotateImg(this,'right',canvas);//轉兩次
rotateImg(this,'right',canvas);
break;
}
}
/*var mpImg = new MegaPixImage(image);
mpImg.render(canvas, {
maxWidth: 800,
maxHeight: 1200,
quality: 0.8,
orientation: 8
});*/
base64 = canvas.toDataURL("image/jpeg", 0.8);
console.log(base64)
}else if (navigator.userAgent.match(/Android/i)) {// 修復android
//alert(Orientation);
// var encoder = new JPEGEncoder();
// base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
// console.log(base64)
if(Orientation != "" && Orientation != 1){
//alert('旋轉處理');
switch(Orientation){
case 6://需要順時針(向左)90度旋轉
// alert('需要順時針(向左)90度旋轉');
rotateImg(this,'left',canvas);
break;
case 8://需要逆時針(向右)90度旋轉
// alert('需要順時針(向右)90度旋轉');
rotateImg(this,'right',canvas);
break;
case 3://需要180度旋轉
// alert('需要180度旋轉');
rotateImg(this,'right',canvas);//轉兩次
rotateImg(this,'right',canvas);
break;
}
}
// var mpImg = new MegaPixImage(image);
// image.render(canvas, {
// maxWidth: 800,
// maxHeight: 1200,
// quality: 0.8,
// orientation: Orientation
// });
base64 = canvas.toDataURL("image/jpeg", 0.9);
var remonew1 = rotateImg(this,'left',canvas);
var remonew2 = rotateImg(this,'right',canvas);
remonew1 = null;
remonew2 = null
}else{
//alert(Orientation);
if(Orientation != "" && Orientation != 1){
//alert('旋轉處理');
switch(Orientation){
case 6://需要順時針(向左)90度旋轉
// alert('需要順時針(向左)90度旋轉');
rotateImg(this,'left',canvas);
break;
case 8://需要逆時針(向右)90度旋轉
// alert('需要順時針(向右)90度旋轉');
rotateImg(this,'right',canvas);
break;
case 3://需要180度旋轉
// alert('需要180度旋轉');
rotateImg(this,'right',canvas);//轉兩次
rotateImg(this,'right',canvas);
break;
}
}
base64 = canvas.toDataURL("image/jpeg", 0.8);
}
fn1(base64)
base64= null;
oReader = null;
image.onload = null
};
};
oReader.readAsDataURL(file);
}
}
//對圖片旋轉處理 added by lzk
function rotateImg(img, direction,canvas) {
//alert(img);
//最小與最大旋轉方向,圖片旋轉4次後回到原方向
var min_step = 0;
var max_step = 3;
//var img = document.getElementById(pid);
if (img == null)return;
//img的高度和寬度不能在img元素隱藏後獲取,否則會出錯
var height = img.height;
var width = img.width;
//var step = img.getAttribute('step');
var step = 2;
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step++;
//旋轉到原位置,即超過最大值
step > max_step && (step = min_step);
} else {
step--;
step < min_step && (step = max_step);
}
//img.setAttribute('step', step);
/*var canvas = document.getElementById('pic_' + pid);
if (canvas == null) {
img.style.display = 'none';
canvas = document.createElement('canvas');
canvas.setAttribute('id', 'pic_' + pid);
img.parentNode.appendChild(canvas);
} */
//旋轉角度以弧度值爲參數
var degree = step * 90 * Math.PI / 180;
var ctx = canvas.getContext('2d');
switch (step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0);
break;
}
var a = rotateImg();
a=null;
}
function urlback(callfn) {
var faceimgcallback = $('.openimg .yindaoshangchuan');
faceimgcallback.eq(0).css('background-image', "url(" + data.front + ")")
var okbaifen = '<div class="zhezhaosen"><div class="mt25 txt13">照片僅供<br>文玩迷後臺審覈使用</div></div>';
$(' body .openimg').append(okbaifen)
faceimgcallback.eq(1).css('background-image', "url(" + data.back + ")")
faceimgcallback.eq(2).css('background-image', "url(" + data.inhand + ")")
var callbacks = '123';
callfn(callbacks)
}
if (data.code == '302') {
console.log('沒有認證過');
// uptokenimages();
democallback()
} else if (data.code == '200') {
console.log(localStorage.getItem('apptoken')+'條連接的token')
console.log('認證過')
//姓名
$('#xingming').val(data.id_name);
//身份證
$('#shenfnezheng').val(data.id_number);
// 認證過的狀態
// 審覈中
if (data.status == '1') {
$('.shenhetime ').show()
$('.shenhetime .shenhezhong').show()
$('.foterbotom').hide();
$('.remodemo').hide();
$('.fortotop').hide();
console.log('審覈中')
// $('body .noupimg').show();
$('body .nomt').css('margin-top', '0')
// #5ea62b
// $('body .noupimg').css('background-color','#5ea62b')
// 遮罩狀態
} else if (data.status == '0') {
// 未通過
democallback()
// uptokenimages();
// 遮罩狀態
urlback(function (data) {
$('body .zhezhao').addClass('z1')
$('body #upload').addClass('z2')
});
console.log('審覈未通過')
$('body .nomt').css('margin-top', '0')
$('body .noupimg').text(data.reason);
$('body .noupimg').show();
// $('#xingming').val(dat.id_name)
} else {
// 通過
// 名字拆解
var basename = data.id_name;
var namelength = basename.length;
var cpitname = basename.split('');
var newname = '';
if(namelength==3)
{
console.log('三個名字')
newname = '*'+cpitname[1]+cpitname[2]
$('#xingming').val(newname);
console.log(newname)
}else if(namelength==4)
{
newname = '**'+cpitname[2]+cpitname[3]
$('#xingming').val(newname);
console.log('四個名字')
}else if(namelength==2)
{
newname = '*'+cpitname[1]
$('#xingming').val(newname);
}else
{
$('#xingming').val(basename);
}
var html = data.id_number;
var uw = html.replace(/(\w)/g,function(a,b,c,d){return (c>(html.length-7))?'*':a});
$('#shenfnezheng').val(uw)
$('.foterbotom').hide();
$('.remodemo').hide();
$('.fortotop').hide();
$('body .nomt').css('margin-top', '0')
$('.shenhetime').show();
$('.shenhetime .shenhechenggong').show();
}
} else {
console.log('接口請求錯誤')
}
})
});
}
};