uni-app分享图片压缩上传demo,可选择一张或多张图片,也可拍摄照片
uni-app分享图片压缩上传demo,可选择一张或多张图片,也可拍摄照片
2016-08-05更新: 下方的代码是比较OLD的了,是通过js进行图片的剪切 旋转 再生成,效率较低。 后来又整合了一个利用native.js本地接口的压缩代码 ,链接在这。 页面中有详细的说明,需要的童鞋们可以参考以下。
代码整合了
更新日志: 2015-05-09
- 修复了ios下无法获取图片宽高的问题: ios下不在img.onload中是获取不到文件对象的。
新增了最大宽度(高度)的判别,按比例压缩。 具体代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<link href="http://ask.dcloud.net.cn/../../../css/mui.min.css" rel="stylesheet" />
<style type="text/css">
body {
background-color: #efeff4;
}
.mui-content {} .mui-content a {
color: #8F8F94;
}
.mui-content a.active {
color: #007aff;
}
.mui-title {
font-family: simhei;
}
.btn_1 {
position: absolute;
bottom: 100px;
left: 10px;
right: 10px;
}
.btn_2 {
position: absolute;
bottom: 20px;
left: 10px;
right: 10px;
}
.mui-btn-block {
width: 90%;
margin: 0 auto;
}
body {
overflow: hidden;
}
.showimg {
margin: 20px 10px auto 10px;
text-align: center;
}
</style>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">上传身份证照片</h1>
<a class="mui-pull-right mui-icon mui-icon-upload" onclick="imgupgrade()"></a>
</header>
<div class="mui-content">
<div class="showimg">
</div>
<button type="button" class="mui-btn mui-btn-primary mui-btn-block btn_1" onclick="galleryImgs()">从相册中选择图片</button>
<br>
<button type="button" class="mui-btn mui-btn-success mui-btn-block btn_2" onclick="cameraimages()">拍照</button>
</div>
<script src="../../../js/mui.min.js"></script>
<script src="../../../js/binaryajax.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/exif.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/canvasResize.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init();
mui.plusReady(function() {})
//上传单张图片
function galleryImg() {
//每次拍摄或选择图片前清空数组对象
f1.splice(0, f1.length);
document.getElementsByClassName("showimg")[0].innerHTML = null;
// 从相册中选择图片
mui.toast("从相册中选择一张图片");
plus.gallery.pick(function(path) {
showImg(path);
}, function(e) {
mui.toast("取消选择图片");
}, {
filter: "image",
multiple: false
});
}
function galleryImgs() {
//每次拍摄或选择图片前清空数组对象
f1.splice(0, f1.length);
document.getElementsByClassName("showimg")[0].innerHTML = null;
// 从相册中选择图片
mui.toast("从相册中选择不超过两张图片");
plus.gallery.pick(function(e) {
if (e.files.length != 2) {
mui.toast('请选择身份证正面和背面照片共两张');
return false;
}
for (var i in e.files) {
showImg(e.files[i]);
}
}, function(e) {
mui.toast("取消选择图片");
}, {
filter: "image",
multiple: true
});
}
// 拍照添加文件
function cameraimages() {
//每次拍摄或选择图片前清空数组对象
f1.splice(0, f1.length);
document.getElementsByClassName("showimg")[0].innerHTML = null;
var cmr = plus.camera.getCamera();
cmr.captureImage(function(p) {
plus.io.resolveLocalFileSystemURL(p, function(entry) {
var localurl = entry.toLocalURL(); //把拍照的目录路径,变成本地url路径,例如file:///........之类的。
showImg(localurl);
});
}, function(e) {
mui.toast("很抱歉,获取失败 " + e);
});
}
// 全局数组对象,添加文件,用于压缩上传使用
var f1 = new Array();
function showImg(url) {
if (0 != url.toString().indexOf("file://")) {
url = "file://" + url;
}
var div = document.getElementsByClassName("showimg")[0];
var img = new Image();
img.src = url; // 传过来的图片路径在这里用。
img.onclick = function() {
plus.runtime.openFile(url);
};
img.onload = function() {
var tmph = img.height;
var tmpw = img.width;
var isHengTu = tmpw > tmph;
var max = Math.max(tmpw, tmph);
var min = Math.min(tmpw, tmph);
var bili = min / max;
if (max > 1200) {
max = 1200;
min = Math.floor(bili * max);
}
tmph = isHengTu ? min : max;
tmpw = isHengTu ? max : min;
img.style.border = "1px solid rgb(200,199,204)";
img.style.margin = "10px";
img.style.width = "150px";
img.style.height = "150px";
img.onload = null;
plus.io.resolveLocalFileSystemURL(url, function(entry) {
entry.file(function(file) {
console.log(file.size + '--' + file.name);
canvasResize(file, {
width: tmpw,
height: tmph,
crop: false,
quality: 50, //压缩质量
rotate: 0,
callback: function(data, width, height) {
f1.push(data);
img.src = data;
div.appendChild(img);
plus.nativeUI.closeWaiting();
}
});
});
},
function(e) {
plus.nativeUI.closeWaiting();
console.log(e.message);
});
};
};
function imgupgrade() {
mui.toast('后台联调时启用上传功能');
return;
var wt = plus.nativeUI.showWaiting();
var url = '后台地址';
var dataType = 'json';
//发送数据
var data = {
files1: f1 //base64数据
};
mui.post(url, data, success, dataType);
}
//成功响应的回调函数
var success = function(response) {
plus.nativeUI.closeWaiting();
if (response != null) {
alert("上传成功");
}
}
</script>
</body>
</html>
伟子的js代码我放在了附件中。
更多关于uni-app分享图片压缩上传demo,可选择一张或多张图片,也可拍摄照片的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复
更多关于uni-app分享图片压缩上传demo,可选择一张或多张图片,也可拍摄照片的实战教程也可以访问 https://www.itying.com/category-93-b0.html
针对你提出的uni-app分享图片压缩上传的需求,以下是一个基本的代码案例,展示了如何实现选择一张或多张图片、拍摄照片以及图片压缩上传的功能。
首先,确保你的项目已经配置好了uni-app环境,并且已经安装了必要的依赖。
- 页面布局(index.vue):
<template>
<view>
<button @click="chooseImages">选择图片/拍摄照片</button>
<view v-for="(img, index) in images" :key="index">
<image :src="img.path" mode="widthFix" style="width: 100px;"></image>
</view>
<button @click="uploadImages" :disabled="!images.length">上传图片</button>
</view>
</template>
<script>
export default {
data() {
return {
images: []
};
},
methods: {
chooseImages() {
uni.chooseImage({
count: 9, // 最多可以选择的图片张数
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,或者二者都有
success: (res) => {
this.images = res.tempFilePaths;
this.compressAndUpload(); // 可以选择在此处直接压缩上传,或点击上传按钮时上传
}
});
},
compressAndUpload() {
this.images.forEach((imgPath) => {
uni.compressImage({
src: imgPath,
quality: 80, // 压缩质量,范围0~100
success: (res) => {
const compressedPath = res.tempFilePath;
// 此处可以添加上传代码,例如uni.uploadFile
console.log('Compressed Image Path:', compressedPath);
},
fail: (err) => {
console.error('Image Compression Failed:', err);
}
});
});
},
uploadImages() {
// 此处为示例,实际使用时需要根据后端接口进行上传
this.images.forEach((img, index) => {
// 假设已经压缩过,这里直接使用img.path(实际应为压缩后的路径)
uni.uploadFile({
url: 'https://your-server-url/upload', // 替换为你的服务器上传接口
filePath: img.path, // 注意:这里应为压缩后的图片路径
name: 'file',
formData: {
user: 'test'
},
success: (uploadFileRes) => {
console.log('Upload Success:', uploadFileRes);
},
fail: (err) => {
console.error('Upload Failed:', err);
}
});
});
}
}
};
</script>
注意:
uni.chooseImage
方法用于选择图片或拍摄照片。uni.compressImage
方法用于压缩图片。uni.uploadFile
方法用于上传图片到服务器。在实际应用中,你需要根据后端接口的要求调整url
、name
和formData
等参数。- 上述代码示例中,图片压缩和上传是分开进行的,但在实际应用中,你可能需要在压缩成功后立即上传压缩后的图片。这可以通过在
uni.compressImage
的success
回调中添加上传逻辑来实现。