我試圖從輸入框中的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
更新了這個問題,希望能夠更清楚一點 –