簡體   English   中英

如何從dataURL創建圖像文件?

[英]How to create an image file from a dataURL?

我試圖將圖片上傳到Parse.com,我沒有文件,但是有dataURL的文件(因為我調整了圖片的大小),但是需要上傳圖片文件。

歡迎任何提示。

以下是代碼,以獲取更多詳細信息:

// First want to resize the image, where the result is a dataURL
var dataURL;
function resizePicture(file) {    // This file is the original image
    var reader = new FileReader();
    reader.onloadend = function() {
        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function() {
            var MAX_WIDTH = 100;
            var MAX_HEIGHT = 150;
            var tempW = tempImg.width;
            var tempH = tempImg.height;
            if (tempW > tempH) {
                if (tempW > MAX_WIDTH) {
                    tempH *= MAX_WIDTH / tempW;
                    tempW = MAX_WIDTH;
                }
            } else {
                if (tempH > MAX_HEIGHT) {
                    tempW *= MAX_HEIGHT / tempH;
                    tempH = MAX_HEIGHT;
                }
            }
            var canvas = document.createElement('canvas');
            canvas.width = tempW;
            canvas.height = tempH;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0, tempW, tempH);
            dataURL = canvas.toDataURL("image/jpeg"); // How can I convert this dataURL to an image file?
        }
    }
    reader.readAsDataURL(file);
}

// Then,  want to upload the image to Parse.com. 
function savePicture() {
    var name = "productPicture.jpg";
    var parseFile = new Parse.File(name, dataURL); // Here instead of dataURL, I need an image file.
    parseFile.save().then(function() {
            // successful save
        }, function(error) {
            alert("The file either could not be read, or could not be saved to Parse.");
    });
}

根據API文檔Parse.File(name, data, type)

數據

文件的數據,如下所示:

  1. 字節值Numbers的數組,或者
  2. 一個像{base64:“ ...”}這樣的對象,帶有一個base64編碼的字符串。
  3. 使用文件上載控件選擇的File對象。

(3)僅適用於Firefox 3.6 +,Safari 6.0.2 +,Chrome 7+和IE 10+。

從理論上講,這應該起作用:

// get everything after "base64,"
var base64 = dataURL.split('base64,')[1];
var parseFile = new Parse.File(name, { base64: base64 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM