【微信小程序】连续拍照功能实现

embedded/2024/9/22 23:49:25/

前言:
最近在使用uniapp开发小程序>微信小程序,遇到这样一个需求,用户想要连续拍照,拍完之后可以删除照片,保留自己想要的照片,然后上传到服务器上。由于原生的方法只能一个个拍照上传,所以只能自己通过视频流截取帧的方式开发一个拍照功能组件,交互和界面都是自己开发,供项目其他需要的地方使用。现做下记录,以下是完整代码:

// Camera.vue 页面,子组件
<template><view v-if="showCamera" class="page-body"><!--图片预览--><!-- <template v-if="previewSrc"><image @click="handleBack" src="../../static/images/common/back.png" class="close-icon"></image><image :src="previewSrc" class="preview-img"></image></template> --><!--图片上传--><image @click="handleCancel" src="../../static/images/common/close.png" class="close-icon"></image><!--摄像头组件--><cameradevice-position="back"flash="off"ref="camera"class="page-camera"></camera><!--拍照--><image @click="takePhoto" src="../../static/images/common/photo.png" class="photo"></image><!--选择的图片--><view class="select-photo"><template v-if="imageList?.length > 0"><view class="storage"><view v-for="(item, index) in imageList" :key="index" style="position: relative;"><image :src="item.tempImagePath" class="select-img" @click="handlePreviewImg(item)"></image><image @click="handleDelete(index)" src="../../static/images/common/cross.png" class="back-icon"></image></view></view></template><view class="finish" @click="handleFinish">确认</view></view><!--添加水印--><view style="position: absolute; top: -999999px;"><canvas style="width: 60px; height: 60px" id="uploadCanvas" canvas-id="uploadCanvas"></canvas></view></view>
</template><script setup name="MyCamera">import { ref, onMounted, getCurrentInstance } from 'vue'import { getToken } from '@/utils/auth.js'import { useUserStore, useHomeStore } from '@/store/index.js'import { $showToast, validateNull, timestampToDateTime } from '@/utils/index.js'const userStore = useUserStore()const homeStore= useHomeStore()const props = defineProps({showCamera: {type: Boolean,default: false},photos: {type: Array,default: []}})const { proxy } = getCurrentInstance()const imageList = ref([]) // 选择图片const uploadFileArr = ref([]) // 已上传的图片const previewSrc = ref('') // 图片预览const $emit = defineEmits(['handleCancel', 'handleFinish'])onMounted(() => {imageList.value = []uploadFileArr.value = []})// 添加水印const waterMarkerOperate = (filePath) => {const address = '江苏省xxxxx'uni.getImageInfo({src: filePath,success: ress => {let ctx = uni.createCanvasContext('uploadCanvas', proxy);// 将图片绘制到canvas内 60-宽, 60-高const cWidth = 40;const cHeight = 60;ctx.drawImage(filePath, 0, 0, 60, cHeight);const fontSize = 2;ctx.setFillStyle('rgba(128, 128, 128, 0.9)'); // 设置背景色ctx.fillRect(0, 65, cWidth, 34); // 设置背景位置ctx.setFontSize(fontSize); // 设置字体大小ctx.setFillStyle('#FFFFFF'); // 设置字体颜色const lineHeight = 2;  // 行高设置let textToWidth = (ress.width / 3) * 0.01; // 绘制文本的左下角x坐标位置let textToHeight = (ress.height / 3) * 0.1; // 绘制文本的左下角y坐标位置const nowTime = timestampToDateTime(); // 当前日期ctx.fillText(`日     期:${nowTime}`, textToWidth, textToHeight);textToHeight += lineHeight;const lines = [];let line = '';// 遍历字符并拆分行for (const char of address) {const testLine = line + char;const testWidth = ctx.measureText(testLine).width;if (testWidth > 24) {lines.push(line);line = char;} else {line = testLine;}}// 加入最后一行lines.push(line);const addressLabel = '地     址:';for (let i = 0; i < lines.length; i++) {const textLine = lines[i];// 仅在第一行添加地址标签const lineText = i === 0 ? addressLabel + textLine : textLine;ctx.fillText(lineText, textToWidth, textToHeight);textToHeight += lineHeight;}// 绘制完成后,在下一个事件循环将 canvas 内容导出为临时图片地址ctx.draw(false, (() => {setTimeout(() => {uni.canvasToTempFilePath({canvasId: 'uploadCanvas',success: res1 => {// 生成水印imageList.value.push({tempImagePath: res1.tempFilePath})},fail: error => {console.log('错误', error);},}, proxy);}, 500);})())}});}// 拍照const takePhoto = () => {// 最多拍摄6张const totalImages = (imageList.value?.length || 0) + (props.photos?.length || 0);if (totalImages > 5) {$showToast('已达拍照上限')return}uni.createCameraContext().takePhoto({quality: 'high',success: (res) => {waterMarkerOperate(res.tempImagePath)}})}// 拍照完成const handleFinish = async () => {// 调用上传接口const uploadPromises = imageList.value?.map(item => {return new Promise((resolve, reject) => {uni.uploadFile({url: config.baseUrl + '/uploadUrl',filePath: item?.tempImagePath,name: 'file',header: {Authorization: 'Bearer ' + getToken()},success: (res) => {try {const data = JSON.parse(res.data)if (data.fileName) {resolve(data.fileName)}} catch (e) {reject(e)}}})})})const imgList = await Promise.all(uploadPromises);imgList.forEach(img => {uploadFileArr.value.push(img)})$emit('handleFinish', JSON.stringify({uploadFileArr: uploadFileArr.value}))$showToast('上传成功')imageList.value = []uploadFileArr.value = []}// 图片预览const handlePreviewImg = (item) => {previewSrc.value = item?.tempImagePath}// 返回const handleBack = () => {previewSrc.value = ''}// 关闭const handleCancel = () => {imageList.value = []uploadFileArr.value = []$emit('handleCancel')}// 删除图片未上传const handleDelete = (index) => {imageList.value.splice(index, 1)}
</script><style lang="scss">
.page-body {width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 99;background: rgba(0, 0, 0, 0.6);display: flex;justify-content: center;align-items: center;.close-icon {position: absolute;left: 30rpx;top: 100rpx;width: 44rpx;height: 44rpx;z-index: 99;}.page-camera {width: 100%;height: 90%;position: absolute;top: 0;}.photo {width: 140rpx;height: 140rpx;position: absolute;bottom: 256rpx;}.select-photo {width: 100%;height: 180rpx;display: flex;flex-direction: row;align-items: center;margin-bottom: 12rpx;background: #000;position: absolute;bottom: 0;.storage {max-width: 540rpx; overflow-x: auto;display: flex;flex-direction: row;}.finish {width: 120rpx;height: 60rpx;line-height: 60rpx;font-size: 28rpx;color: #fff;text-align: center;position: absolute;right: 37rpx;background: #0fad70;border-radius: 10rpx;}.select-img {width: 120rpx;height: 120rpx;margin-right: 16rpx;border-radius: 10rpx;}.back-icon {width: 30rpx;height: 30rpx;position: absolute;right: 0;top: -10rpx;}}.preview-img {width: 100%;height: auto;object-fit: contain;}
}
</style>// 时间戳转成时间
const timestampToDateTime = (timestamp) => {const date = timestamp ? new Date(timestamp) : /* @__PURE__ */ new Date();const year = date.getFullYear();const month = String(date.getMonth() + 1).padStart(2, "0");const day = String(date.getDate()).padStart(2, "0");const hours = String(date.getHours()).padStart(2, "0");const minutes = String(date.getMinutes()).padStart(2, "0");const seconds = String(date.getSeconds()).padStart(2, "0");return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};// 父组件使用
// index.vue
import Camera from '@/components/Camera.vue'<my-camera ref="cameraRef" showCamera="true" :photos="form.photo" @handleFinish="handleFinish" @handleCancel="handleCancel"></my-camera><script setup>const handleFinish = () => {// 上传图片完成的逻辑处理}const handleCancel = () => {// 上传图片取消的逻辑处理}
</script>

欢迎各位大佬有意见的话评论区留言,互相交流学习~


http://www.ppmy.cn/embedded/115302.html

相关文章

uniapp自定义Tabbar教程

uniapp自定义Tabbar 1、定义tabbar 在pages.json中配置除主要页面地址&#xff0c; "tabBar": {"custom": true,"list": [{"pagePath": "pages/home/index"},{"pagePath": "pages/user-center/index"…

Linux:虚拟文件系统/proc和self进程

相关阅读 Linuxhttps://blog.csdn.net/weixin_45791458/category_12234591.html?spm1001.2014.3001.5482 /proc目录 在Linux操作系统中&#xff0c;目录/proc是一个虚拟文件系统&#xff0c;称为procfc&#xff0c;用于访问内核和系统的实时状态信息。这个文件系统不同于常规…

Microsoft 365 Copilot: Wave 2 发布,开启AI时代下的全新工作流

本周一&#xff08;9月16日&#xff09;&#xff0c;微软对 Microsoft 365 Copilot 办公辅助工具进行了重大升级&#xff0c;推出 Wave 2 版本。新版 Copilot 将为 Microsoft 365 用户带来一系列新功能和改进&#xff0c;进一步提升工作效率与用户体验&#xff0c;正式开启AI时…

【计算机网络】初识网络

初识网络 初识网络网络的发展局域网广域网 网络基础IP地址端口号协议五元组协议分层OSI 七层模型TCP/IP五层模型封装和分用"客户段-服务器"结构 初识网络 网络的发展 在过去网络还没有出现的时候, 我们的计算机大部分都是独自运行的, 比如以前那些老游戏, 都是只能…

用Inno Setup打包QT程序输出安装包

InnoSetup打包编译好的QT程序 文章目录 InnoSetup打包编译好的QT程序介绍具体步骤自定义脚本更改引入配置文件/动态库路径申请管理员权限设置安装过程界面的图标和图片C程序依赖运行库 介绍 Inno Setup&#xff1a;用于打包安装程序 具体步骤 首先打开inno setup compiler 第…

Qt容器类控件——QGroupBox和QTabWidget

文章目录 QGroupBox又来点餐QTabWidget使用演示 QGroupBox 容器类控件即里面可以容纳其他的控件 QGroupBox叫做分组框&#xff0c;可以把其他控件放在里面作为一组 QGroupBox的存在&#xff0c;只是为了让界面更好看一点&#xff0c;并不实现实质性的功能。 当界面较复杂的时候…

鸿蒙OpenHarmony【轻量系统内核扩展组件(CPU占用率)】子系统开发

基本概念 CPU&#xff08;中央处理器&#xff0c;Central Processing Unit&#xff09;占用率分为系统CPU占用率和任务CPU占用率。 系统CPU占用率&#xff1a;是指周期时间内系统的CPU占用率&#xff0c;用于表示系统一段时间内的闲忙程度&#xff0c;也表示CPU的负载情况。系…

小米,B站网络安全岗位笔试题目+答案

《网安面试指南》http://mp.weixin.qq.com/s?__bizMzkwNjY1Mzc0Nw&mid2247484339&idx1&sn356300f169de74e7a778b04bfbbbd0ab&chksmc0e47aeff793f3f9a5f7abcfa57695e8944e52bca2de2c7a3eb1aecb3c1e6b9cb6abe509d51f&scene21#wechat_redirect 《Java代码审…