首页 > 解决方案 > 尝试将图像存储为 base64 并使用它

问题描述

我在网上找到了一段代码,它似乎可以同时工作但不能同时工作。我认为这可能是我缺乏理解,但我似乎无法让它按照我想要的方式工作。

selectPicture() {               
                let context = imagepicker.create({
                    mode: "single" // use "multiple" for multiple selection
                });
                var imageBase64
                context
                .authorize()
                .then(function() {
                    return context.present();
                })
                .then(function(selection) {
                    selection.forEach(function(selected) {
                        imageSourceModule.fromAsset(selected).then((imageSource) => {
                            
                            imageBase64 = imageSource.toBase64String("jpg",60);
                            console.log("Image saved successfully!")
                            console.log(imageBase64)
                            console.log("test test") //runs fine
                            this.image = "~/assets/images/account/camera.png" //cant seem to run
                            console.log("test test 2")
                        }).catch(function (e) {
                            // process error
                            console.log("got error 1")
                        });
                    })
                }).catch(function (e) {
                    // process error
                    console.log("got error 2")
                });

            },

在 中imageSourceModule.fromAsset(selected).then((imageSource),我试图将 base64 信息保存在另一个变量中,但除了控制台日志字符串之外似乎无法做任何事情。例如,当我运行时this.image = "~/assets/images/account/camera.png"(只是一个占位符,即使调用一个方法也不起作用),它会捕获一个错误。

问题可能是什么?谢谢你!

更新

我更改console.log("got error 1")为记录实际更新,我得到的是:

undefined 不是对象(评估 'this.image = "~/assets/images/account/camera.png"')*

我现在认为我对外部调用变量的理解存在问题。我的变量“图像”在脚本中

data() {
            return {
                image : ""
            }
        }

标签: iosimagevue.jsbase64nativescript

解决方案


首先检查this变量是什么,因为你不使用 es6箭头函数,所以this可能不是 vue 实例。第二件事:当您异步更改 vue 变量时,请使用$set方法,例如:this.$set(this, 'image', '~/assets/images/account/camera.png')


推荐阅读