2

我正在尝试将图像保存到 Dropbox,但无法正确转换。我有一个 img(使用示例捕获),我想将其存储到接受 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 感谢您的帮助

拉尔西

4

1 回答 1

0

将我的评论移至答案,因为这似乎适用于最新的 Datastore JS SDK,但可能不适用于 dropbox.js 0.10.2。


什么浏览器和什么版本的 Dropbox 库?保存的图像有什么问题?(我假设“损坏”是指它不会在您使用的任何工具中打开......还有更多提示吗?文件大小合理吗?)我刚刚做了一个非常相似的测试(toDataURL、atob 和 Uint8Array ) 在 OS X 和 dropbox.com/static/api/dropbox-datastores-1.0-latest.js 上使用 Chrome,它似乎可以工作。

于 2013-12-20T17:04:37.233 回答