繁体   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