hi, 欢迎访问我的博客

uniapp 截屏扫码

最近开发功能遇到个需求,用户点击某个操作之后,需要截取当前屏幕内容,并扫码识别屏幕截图中的二维码,代码如下:

首先将代码抽离到外部文件中,以便复用:

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
// 截图
export function takeScreenshot() {
    return new Promise(resolve => {
        var pages = getCurrentPages() //获取当前页面信息
        var page = pages[pages.length - 1]
        var bitmap = null
        var currentWebview = page.$getAppWebview()
        bitmap = new plus.nativeObj.Bitmap('amway_img')
        // 将webview内容绘制到Bitmap对象中
        currentWebview.draw(bitmap, function() {
            // console.log('截屏绘制图片成功');
            let rand = Math.floor(Math.random() * 10000)
            let saveUrl = '_doc/' + rand + 'a.jpg'
            // resolve(saveUrl)
            bitmap.save(saveUrl, {}, function(i) {
                resolve(i.target)
            }, function(e) {
                resolve(false)
                console.log('保存图片失败:' + JSON.stringify(e))
            })
        }, function(e) {
            resolve(false)
            console.log('截屏绘制图片失败:' + JSON.stringify(e))
        })
    })
}
 
// 扫描本地二维码
export function scanLocalImgCode(url) {
    return new Promise(resolve => {
        uni.getImageInfo({
            src: url,
            success: function(image) {
                plus.barcode.scan(image.path, function(type, result) {
                    resolve(result)
                    console.log('扫描成功:(' + type + ')' + result)
                }, function(e) {
                    resolve(false)
                    console.log('扫描失败: ' + JSON.stringify(e))
                })
            }
        })
    })
}

  页面中使用

 

1
2
3
4
5
6
7
8
9
10
11
12
// 扫码
async handleScan() {
    const imgPath = await takeScreenshot()
    if (imgPath) {
        const codeContent = await scanLocalImgCode(imgPath)
        if (codeContent) {
            console.log(codeContent);
        } else {
            this.$toast('扫码失败,请确保二维码在屏幕中完整显示哦', 2000)
        }
    }
},

  

posted @   打静爵  阅读(485)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示