本示例代码,为我爱模板网在项目中使用的,mui拍照或从相册选择照片,并且对照片进行1倍压缩,最终得到base64为图片地址的代码。这里的图片压缩,用的是
jpgtobase64.js插件(点击下载),它的原理很简单,就是利用html5的canvas,将图片放到canvas画布上,再进行缩放得到结果,代码已经在文章末尾提供。废话不多说,直接上代码:
<script src="js/mui.min.js"></script>
<script src="js/jpgtobase64.js"></script>
<script>
var photo; //用以接收图片最终地址
//弹出选择拍照还是从相册获取
document.querySelector('#upload').addEventListener('tap', function(){
var buttonTit = [{
title: "拍照"
}, {
title: "从手机相册选择"
}];
plus.nativeUI.actionSheet({
title: "上传图片",
cancel: "取消",
buttons: buttonTit
}, function(b) { /*actionSheet 按钮点击事件*/
switch (b.index) {
case 0:
break;
case 1:
getImage(); /*拍照*/
break;
case 2:
galleryImg();/*打开相册*/
break;
default:
break;
}
})
})
//拍照
function getImage(){
var cmr = plus.camera.getCamera(1); //获取后面的摄像头
cmr.captureImage(function(p) {
//拍照成功,返回路径 p,但是不是绝对路径
//通过p,读取图片文件
plus.io.resolveLocalFileSystemURL(p, function(entry) {
//entry为获取的文件,.file()方法可以获取该文件的文件名、大小等信息,返回包含文件信息的对象
entry.file(function (file) {
//alert("getFile:" + JSON.stringify(file));
var fileReader = new plus.io.FileReader(); //开启读取文件
fileReader.readAsDataURL(file, 'utf-8'); //将文件数据对象信息file进行url base64编码
fileReader.onloadend = function (evt) {
//压缩图片
convertImgToBase64(evt.target.result, function (retImg) {
photo = retImg;
document.querySelector('.uploaded-imgs').innerHTML += '<span><img src="'+photo+'"></span>';
});
}
})
}, function(e) {
alert(e.message);
});
},function(e) {}, {
filename: "_doc/camera/"
}); //拍照
}
//从相册选择
function galleryImg(){
plus.gallery.pick(function(e){
for(var i in e.files){
var fileSrc = e.files[i];
//压缩图片
convertImgToBase64(fileSrc, function (retImg) {
photo = retImg;
document.querySelector('.uploaded-imgs').innerHTML += '<span><img src="'+photo+'"></span>';
});
}
}, function (e) {
console.log( "取消选择图片" );
},{
filter: "image",
multiple: true,
maximum: 1,
system: false,
onmaxed: function() {
plus.nativeUI.alert('最多只能选择1张图片');
}
});
}
</script>
附上:jpgtobase64.js代码:
function convertImgToBase64(url, callback, outputFormat) {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function () {
var width = img.width;
var height = img.height;
// 按比例压缩1倍
var rate = (width < height ? width / height : height / width) / 1;
canvas.width = width * rate;
canvas.height = height * rate;
ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}