应用场景:收集用户的人脸图片,用于做身份识别等功能
技术支持:1.HTML媒体捕获(capture),可参考https://www.w3.org/TR/html-media-capture/
2.form表单向服务器提交数据
3.exif.js读取图像的元数据
4.识别iphoneX设备
5.图片资源加载完毕事件
源代码:
HTML
<label for="facecoll_form_afile"></label>
<form action="serveradress" method="post" name="image" id="facecoll_form">
<input name="image" class="facecoll_camera" id="facecoll_form_afile"
accept="image/*" type="file" capture="camera" style="display:none;"/>
<input name="file_type" value="image" type="hidden"/>
<input name="token" value="" id="image_token_input" type="hidden"/>
</form>
JS
$('.facecoll_camera').change(function(event) {
//将图片上传至服务器
$('#facecoll_form').ajaxSubmit({
dataType: 'json',
success: function(data) {
//获取从服务器中返回的图片地址
...
//将图片放在页面上
...
//调用方法将图片进行旋转
rotate_img();
},
error: function(data) {
layer.closeAll('loading');
}
});
});
//将图片进行旋转,从设备上直接获取的图片不能直接放在页面上,需要旋转之后才能放在页面上
//有一种特殊的情况是在iphoneX系列的手机上不用做旋转处理,因为iphoneX系列的手机在拍的时候就自己做
//了旋转(这个特性无力吐槽!!!)
function rotate_img() {
if (is_iphonex()) {
return '';
}
var img = $('img');
img.load(function() {
var img_style = {};
EXIF.getData(this, function(){
var Orientation = EXIF.getTag(this, 'Orientation');
if (Orientation == 6) {
img_style.transform = 'rotate(90deg)';
img_style['margin-left'] = '-10px';
} else if (Orientation == 8) {
img_style.transform = 'rotate(270deg)';
img_style['margin-left'] = '-10px';
img_style['margin-top'] = '12px';
}
$(this).css(img_style);
});
})
}
//判断手机是不是iphoneX
function is_iphonex() {
var u = navigator.userAgent;
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
var flag = false;
if (isIOS) {
//是iphoneX
if (screen.height == 812 || screen.height == 896){
flag = true;
}
}
return flag;
}
备注: 1.exif.js ,直接可以在官网找到下载地址,就不再贴了
2.form表单向服务器提交数据,具体的细节相关的文章很多,就不再造轮子了
3.识别iphoneX设备,目前实例提供的方法比较有局限性,由于测试样例有限只有812和896两个样本,这个方法有风险
4.自拍和后摄像头拍摄图片对应的Orientation值是不同的,旋转的角度也不同。
5.此案例具体实施在小米、华为、iphone8、iphoneX上都可以运行