【问题标题】:Convert image into base64string in visualstudio apache cordova在visual studio apache cordova中将图像转换为base64字符串
【发布时间】:2016-02-08 16:57:50
【问题描述】:

我正在开发 VS2015 cordova 应用程序。当我从图库中获取图像并将其转换为 base64string 时出现问题。我成功获得了base64string,但是当我显示它时,我总是得到黑色图像。这是我的代码:

    function onPhotoURISuccess(imageURI) {
     var largeImage = document.getElementById('smallImage');
    largeImage.style.display = 'block';
    largeImage.src = imageURI;
    basestrg = encodeImageUri(imageURI);

}

function getPhoto(source) {
           navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        destinationType: Camera.DestinationType.NATIVE_URI, mediaType: Camera.MediaType.Photo,
        sourceType: source
    });
}
function encodeImageUri(imageUri) {
    var c = document.createElement('canvas');
    var ctx = c.getContext("2d");
    var img = new Image();
    img.onload = function () {
        c.width = this.width;
        c.height = this.height;
        ctx.drawImage(img, 0, 0);
    };
    img.src = imageUri;
    var dataURL = c.toDataURL("image/jpeg");
    return dataURL;
}

任何想法

【问题讨论】:

    标签: jquery cordova phonegap-plugins visual-studio-cordova


    【解决方案1】:

    我试图让您的特定代码正常工作,但我看到黑匣子的最终结果相同。

    不过,我认为有一种更简单的方法可以实现您的目标。您可以使用一个名为DATA_URL 的选项,而不是将NATIVE_URI 作为目标类型传入。这个DATA_URL 选项将为您提供base64 编码的字符串,然后您可以在图像元素中使用该字符串。

    当我将它放在您的getPhoto() 函数中时,这是一些对我有用的代码。我改编自Cordova Camera Plugin Documentation

    navigator.camera.getPicture(onSuccess, onFail, {
        destinationType: Camera.DestinationType.DATA_URL,
        mediaType: Camera.MediaType.PICTURE,
        sourceType: source
    });
    
    function onSuccess(imageData) {
        var image: any = document.getElementById('myPicture');
        image.src = "data:image/jpeg;base64," + imageData;
    }
    
    function onFail(message) {
        alert('Failed because: ' + message);
    }
    

    【讨论】:

    • 它工作正常,但是当我从画廊上传图像时,有什么办法可以降低图像的分辨率?
    • 有趣的问题 - 您的目标是在将其上传到另一台服务器时降低分辨率吗?如果是这样,那么我看到你想用 Canvas 做什么,这似乎是一个解决方案,如果你能越过黑匣子(我不知道该怎么做)
    猜你喜欢
    • 2018-09-07
    • 2014-07-21
    • 2019-04-07
    • 2013-07-04
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多