我试图从输入框中的URL获取图像。实质上,我想将图像URL转换为文件对象。JavaScript:将图像URL转换为文件对象
为了便于比较,如果您访问Google图片并选择一张随机图片,则可以复制图片或图片的网址。
在我的情况下,用户会抓住该URL(如https://pbs.twimg.com/profile_images/638751551457103872/KN-NzuRl.png
)并粘贴到输入框中,然后单击我的“添加图像”按钮。我想本地访问这个图像文件的URL,我可以传递到ng-file-upload
的一个函数Upload.dataUrl(myImageFile)
,它将为我做上传。
目前,我已经检查过,以确保它的网址是一个有效的图像,但我不知道如何得到图像(图像的URL与图像)。
formSubmit: function(){
var url = document.forms["imageForm"].elements["urlImage"].value;
console.log(url);
if (!$scope.checkURL(url)) {
console.log("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.")
return(false);
}
$scope.testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
console.log("SUCCESS!");
//document.forms["submitForm"].submit();
//!!!---------------------!!!
//Correct URL link, but not sure how to get the image from URL
//!!!---------------------!!!
}
else if (result == "error") {
console.log("The image URL does not point to an image or the correct type of image.");
}
else {
console.log("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
},
checkURL: function(url){
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
},
testImage: function(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
任何援助将不胜感激!
什么* *正是你说的意思*“获取图像” *?你的意思是二进制数据吗? – Phil
更新了这个问题,希望能够更清楚一点 –