使用html5+的plus调起相机拍照,使用canvas压缩图片,转成base64传到后台
生活随笔
收集整理的這篇文章主要介紹了
使用html5+的plus调起相机拍照,使用canvas压缩图片,转成base64传到后台
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
html代碼:
<div class="form-com door"><label for="">門頭照:</label><a href="javascript:void(0);" onclick="getImage(1)"><img id="img1" class="img" src="" alt=""></a></div><div class="form-com licence"><label for="">營業執照:</label><a href="javascript:void(0);" onclick="getImage(2)"><!-- <input class="upload-img" type="file" onchange="setimgsrc(this,'img1');" accept="image/*" capture="camera"> --><img id="img2" class="img" src="" alt=""></a></div><div class="form-com shop-panorama"><label for="">店鋪全景:</label><a href="javascript:void(0);" onclick="getImage(3)"><img id="img3" class="img" src="" alt=""></a></div>js代碼:
// 初始化plusdocument.addEventListener( "plusready", onPlusReady, false );// 擴展API加載完畢,現在可以正常調用擴展API function onPlusReady() {console.log("plusready");}// 調用手機的拍照功能function getImage(obj){ var cmr = plus.camera.getCamera();cmr.captureImage(function(p){plus.io.resolveLocalFileSystemURL(p, function(entry){img=document.getElementById("img"+obj);img.src=entry.toLocalURL();img.style.opacity = 1;}, function(e){outLine('讀取拍照文件錯誤:'+e.message);});}, function(e){}, {filename:'_doc/camera/',index:1}); }// 用convas繪制圖片function dealImage(path, obj, callback){var img = new Image();img.src = path;img.onload = function(){var that = this;// 默認按比例壓縮var w = that.width,h = that.height,scale = w / h;w = obj.width || w;h = obj.height || (w / scale);var quality = 0.5; // 默認圖片質量為0.7//生成canvasvar canvas = document.createElement('canvas');var ctx = canvas.getContext('2d');// 創建屬性節點var anw = document.createAttribute("width");anw.nodeValue = w;var anh = document.createAttribute("height");anh.nodeValue = h;canvas.setAttributeNode(anw);canvas.setAttributeNode(anh); ctx.drawImage(that, 0, 0, w, h);// 圖像質量if(obj.quality && obj.quality <= 1 && obj.quality > 0){quality = obj.quality;}// quality值越小,所繪制出的圖像越模糊var base64 = canvas.toDataURL('image/jpeg', quality );// 回調函數返回base64的值callback(base64);}}var time = null;var view = '';var view1 = '';var view2 = '';// 提交注冊的信息$(document).on('click','.submit button',function(){dealImage($('#img1').attr('src'),$('#img1')[0],function(base641){view = base641;});dealImage($('#img2').attr('src'),$('#img2')[0],function(base642){view1 = base642;});dealImage($('#img3').attr('src'),$('#img3')[0],function(base643){view2 = base643; });time = setTimeout(function(){httppost(view,view1,view2);},2000);}); 到此處調用手機拍照,壓縮并上傳到后臺完成,view,view1,view2分別是basse64總結
以上是生活随笔為你收集整理的使用html5+的plus调起相机拍照,使用canvas压缩图片,转成base64传到后台的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序---实现输入手机验证码功能
- 下一篇: hbuilder热更新