我試圖將圖像保存到保管箱,並無法正確獲取轉換。我有一個img(捕獲使用this示例),我想將它存儲到接受ArrayBuffer的Dropbox(示例here)保存捕獲的PNG作爲arraybuffer
這是我發現應該進行兩次轉換的代碼,首先轉換爲base64,然後轉換爲一個ArrayBuffer
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
function base64ToArrayBuffer(string_base64) {
var binary_string = window.atob(string_base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
var ascii = binary_string.charCodeAt(i);
bytes[i] = ascii;
}
return bytes.buffer;
}
儲蓄開始這樣
var img = $('#show-picture')[0];
var data = base64ToArrayBuffer(getBase64Image(img));
dropbox.client.writeFile(moment().format('YYYYMMDD-HH-mm-ss')+'.png', data, function (error, stat) {
if (error) {
return dropbax.handleError(error);
}
// The image has been succesfully written.
});
問題是,我得到保存損壞的文件,是對什麼是錯有點糊塗了。
* 編輯*
這裏的鏈接到原始文件 https://www.dropbox.com/s/ekyhvu2t6d8ldh3/original.PNG這裏的損壞。 https://www.dropbox.com/s/f0oevj1z33brpur/20131219-22-23-14.png
我使用這個版本的dropbox.js的://cdnjs.cloudflare.com/ajax/libs/dropbox.js/0.10.2/dropbox.min.js
正如你所看到的損壞的是略低更大23,3KB VS 32.6 KB 感謝所有幫助
Larsi
什麼瀏覽器和什麼版本的Dropbox庫?那麼保存的圖像有什麼問題? (我通過「損壞」假設你的意思是它不會在你使用的任何工具中打開......更多提示?文件大小是否合理?)我只做了一個非常類似的測試('toDataURL','atob '和'Uint8Array')與OS X和https://www.dropbox.com/static/api/dropbox-datastores-1.0-latest.js,它似乎工作。 – smarx
Hi @smarx!感謝您查看這個。我添加了原始和損壞文件的鏈接 – Larsi
@smarx我剛剛嘗試了最新的dropbox.js及其工作。感謝您的更新。發佈一個答案,我會接受它。 – Larsi