【问题标题】:JavaScript: Transform image URL into File ObjectJavaScript:将图像 URL 转换为文件对象
【发布时间】:2016-02-14 11:27:08
【问题描述】:

我正在尝试从输入框中的 URL 获取图像。本质上,我想将图像 URL 转换为文件对象。

为了比较,如果您访问 Google 图片并选择随机图片,您将能够复制图片或图片的网址。

在我的例子中,用户会抓取该 URL(例如 https://pbs.twimg.com/profile_images/638751551457103872/KN-NzuRl.png)并粘贴到输入框中,然后单击我的“添加图像”按钮。我想从 URL 本地访问这个图像文件,我可以将它传递给来自 ng-file-upload 的一个名为 Upload.dataUrl(myImageFile) 的函数,该函数将为我完成上传。

目前,我已检查以确保 URL 是有效图片,但我不确定如何获取图片(图片 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); 
    }

任何帮助将不胜感激!

【问题讨论】:

  • “获取图像” 是什么意思?你是说二进制数据吗?
  • 更新了问题,希望更清楚一点

标签: javascript ajax image url download


【解决方案1】:

你也不需要太难
很简单

document.getElementById("myImage").src = document.myform.myinput.value;

【讨论】:

  • 感觉好像需要做一个http.get()才能真正获取用户输入的url来获取图片
猜你喜欢
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2020-07-26
  • 1970-01-01
  • 2022-11-11
  • 2020-02-21
相关资源
最近更新 更多