【Demo】HTML5 拍照上传
本文主要讲解 手机浏览器 如何拍照
为什么会有这个需求
最近做一个项目要用到拍照然后上传照片,但是网页拍照一般都是用Flash做的,而我们主要是H5页面,如果在微信里面有权限就可以通过JSSDK调起摄像头拍照的。这里我们主要说下手机端浏览器如何调起摄像头
H5如何打开摄像头
不需要特别的支持,只需要一行代码就可以了
1 | < input id="upload" type="file" accept="image/*;" capture="camera" > |
如何预览图
原理是用js获取input file的图像流,然后赋给img标签的src属性,然后再设置这个img的css,就能得到你要的效果了,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | ; var demo_h5_upload_ops = { init: function (){ this .eventBind(); }, eventBind: function (){ var that = this ; $( "#upload" ).change( function (){ var reader = new FileReader(); reader.onload = function (e) { that.compress( this .result); }; reader.readAsDataURL( this .files[0]); }); }, compress : function (res) { var that = this ; var img = new Image(), maxH = 300; img.onload = function () { var cvs = document.createElement( 'canvas' ), ctx = cvs.getContext( '2d' ); if (img.height > maxH) { img.width *= maxH / img.height; img.height = maxH; } cvs.width = img.width; cvs.height = img.height; ctx.clearRect(0, 0, cvs.width, cvs.height); ctx.drawImage(img, 0, 0, img.width, img.height); var dataUrl = cvs.toDataURL( 'image/jpeg' , 1); $( ".img_wrap" ).attr( "src" ,dataUrl); $( ".img_wrap" ).show(); // 上传略 that.upload( dataUrl ); }; img.src = res; }, upload: function ( image_data ){ /*这里写上次方法,图片流是base64_encode的*/ } }; $(document).ready( function (){ demo_h5_upload_ops.init(); } ); |
实例演示
地址:http://m.54php.cn/demo/h5_upload 也可以手机扫描下图
测试结果报告
手机 | UC浏览器 | 微信 |
IOS |
支持拍照上传 支持图库选择上上传 |
支持拍照上传 支持图库选择上传 |
Android |
支持拍照上传 支持图库选择上传 |
不支持拍照上传 支持图库选择上传 |
效果图
本人IOS 系统 亲自测试了UC浏览器和微信自带浏览器 完美兼容
原文地址:【Demo】HTML5 拍照上传
标签:demo h5 拍照 html5 上传
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步