gpt4 book ai didi

javascript - 如何从 dataURL 创建图像文件?

转载 作者:行者123 更新时间:2023-11-29 18:14:26 25 4
gpt4 key购买 nike

我正在尝试将图片上传到 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 Documentation对于 Parse.File(name, data, type):

data

The data for the file, as either:

  1. an Array of byte value Numbers, or
  2. an Object like { base64: "..." } with a base64-encoded String.
  3. a File object selected with a file upload control.

(3) only works in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.

理论上这应该可行:

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

关于javascript - 如何从 dataURL 创建图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24626177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com