2013-12-19 64 views
2

我試圖將圖像保存到保管箱,並無法正確獲取轉換。我有一個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

+0

什麼瀏覽器和什麼版本的Dropbox庫?那麼保存的圖像有什麼問題? (我通過「損壞」假設你的意思是它不會在你使用的任何工具中打開......更多提示?文件大小是否合理?)我只做了一個非常類似的測試('toDataURL','atob '和'Uint8Array')與OS X和https://www.dropbox.com/static/api/dropbox-datastores-1.0-latest.js,它似乎工作。 – smarx

+0

Hi @smarx!感謝您查看這個。我添加了原始和損壞文件的鏈接 – Larsi

+0

@smarx我剛剛嘗試了最新的dropbox.js及其工作。感謝您的更新。發佈一個答案,我會接受它。 – Larsi

回答

0

移動我的評論一個答案,因爲它似乎是這部作品在最新的數據存儲JS SDK但也許不dropbox.js 0.10.2。


什麼瀏覽器和哪個版本的Dropbox庫?那麼保存的圖像有什麼問題? (我認爲「損壞」你的意思是它不會打開你使用的任何工具...更多的提示?文件大小是否合理?)我只是做了一個非常類似的測試(toDataURL,atob和Uint8Array )與OS X上的Chrome和dropbox.com/static/api/dropbox-datastores-1.0-latest.js,它似乎工作。

+0

我用canvas.toDataURL('PNG'),並將其存儲在一個變量:數據,然後我編碼client.writeFile('image.png',數據,回調)...文件被終止,但它已損壞,即沒有要顯示的內容。什麼可能是錯誤? – softvar

+0

請幫幫我! – softvar

+0

數據URL與您要在PNG中存儲的數據不同。具體來說,它是一個base64編碼版本的數據,帶有前綴URL方案和MIME類型。在上面的問題中,代碼正確,顯示瞭如何將數據URL轉換爲實際的基礎數據並將其保存到Dropbox。 – smarx