使用画布中的数据将图片保存到收存箱 [英] Save image to dropbox with data from canvas
问题描述
我试图将canvas数据作为图像(png)写入我的保管箱。
我设法从canvas获取数据并将文件保存到dropbox,但该文件不是它接缝的图像文件。
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.
根据文档,图像数据应该转换为arrayBuffer。我正在使用一个函数在这里发现在Stackoverflow,但东西似乎不工作。
有人知道我在做什么吗?
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!');
}
});
这里有一些dropbox文档。
https://github.com/dropbox/dropbox -js / blob / stable / guides / snippets.md
Here's some dropbox documentation. https://github.com/dropbox/dropbox-js/blob/stable/guides/snippets.md
推荐答案
我使用另一个函数将base64转换为bufferArray,并从字符串中删除'data:image / png; base64',它工作。希望这将有助于未来的其他人。
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!');
}
});
这篇关于使用画布中的数据将图片保存到收存箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!