I'm trying to write canvas data as an image (png) to my dropbox. I manage to get the data from canvas and to save a file to dropbox, but the file is not an image file it seams.
According to the documentation the image data should be converted to a arrayBuffer. That I'm doing using a function found here on Stackoverflow but something doesn't seem to work. Does anyone know what I'm doing wrong?
function _str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function _savePicture () {
//Get data from canvas
var imageSringData = canvas.toDataURL('image/png');
//Convert it to an arraybuffer
var imageData = _str2ab(imageSringData);
client.writeFile('/Public/the_image.png', imageData, function(error, stat) {
if (error) {
console.log('Error: ' + error);
} else {
console.log('File written successfully!');
}
});
Here's some dropbox documentation. https://github.com/dropbox/dropbox-js/blob/stable/guides/snippets.md
Got it to work finally! I used another function to convert base64 to bufferArray and remove the 'data:image/png;base64,' from the string and it worked. Hopefully this will help someone else in the future.
function _base64ToArrayBuffer(base64) {
base64 = base64.split('data:image/png;base64,').join('');
var binary_string = window.atob(base64),
len = binary_string.length,
bytes = new Uint8Array( len ),
i;
for (i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function _savePicture () {
//Get data from canvas
var imageSringData = canvas.toDataURL('image/png');
//Convert it to an arraybuffer
var imageData = _base64ToArrayBuffer(imageSringData);
client.writeFile('/Public/the_image.png', imageData, function(error, stat) {
if (error) {
console.log('Error: ' + error);
} else {
console.log('File written successfully!');
}
});
来源:https://stackoverflow.com/questions/27524283/save-image-to-dropbox-with-data-from-canvas