Phonegap encode image base64

后端 未结 3 1351
别跟我提以往
别跟我提以往 2021-01-18 22:44

I\'m trying to encode an image to base64 and send it to a server. When I retrieve the image all it shows is blank.

The code I\'m using to encode it is this:

3条回答
  •  庸人自扰
    2021-01-18 22:51

    The image is loading asynchronously, meaning that your return dataURL... happens before the image is loaded into the canvas.

    Instead of having this function return a value, have it call a callback function.

    encodeImageUri = function(imageUri, callback) {
        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);
    
            if(typeof callback === 'function'){
                var dataURL = c.toDataURL("image/jpeg");
                callback(dataURL.slice(22, dataURL.length));
            }
        };
        img.src = imageUri;
    }
    

    You now call it like this:

    encodeImageUri('/path/to/image.png', function(base64){
        // Do something with the b64'd image
    });
    

    NOTE: For this to work, the image needs to be on the same domain as your page.

提交回复
热议问题