apicloud 图片转base64格式

function convert2Base64(photoPath, callback) {
        // console.info("convert2Base64...");
        var trans = api.require('trans');
        if (trans == null) {
            console.info("找不到插件trans");
            return;
        }
        trans.decodeImgToBase64({
            imgPath: photoPath
        }, function (ret, err) {
            if (ret.status) {
                if (callback) callback("data:image/jpg;base64," + ret.base64Str)
            } else {
                console.error("图片转换失败:" + err.msg);
                console.log(JSON.stringify(err));
                // 如果转换失败,使用下边兼容方式再转换一次
                //console.info("photoPath", photoPath);
                //相册内图片被拷贝到临时文件夹,返回已拷贝图片的绝对路径
                var UIAlbumBrowser = api.require('UIAlbumBrowser');
                UIAlbumBrowser.transPath({
                    path: photoPath
                }, function (ret, err) {
                    if (ret) {
                        var img = document.createElement("img");
                        img.onload = function () {
                            var canvas = document.createElement("canvas");
                            canvas.width = img.width;
                            canvas.height = img.height;
                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(img, 0, 0, img.width, img.height);
                            var dataURL = canvas.toDataURL("image/jpeg");
                            //console.info("onload..", dataURL);
                            if (callback) callback(dataURL);
                        }
                        img.src = ret.path;
                    } else {
                        console.info(JSON.stringify(err));
                    }
                });
            }
        });
    }

  

posted @ 2021-07-06 10:52  居无常  阅读(247)  评论(0编辑  收藏  举报