从本地 URL 获取数据 URL

Get the Data URL from a local url

本文关键字:URL 获取 数据      更新时间:2023-09-26

我正在用Cordova,Ionic,Angular和Sqlite作为客户端数据库编写一个Web应用程序。

我正在做一个用于拍照的模块,并尝试从拍摄的图像中获取和发送 Base64 编码(数据 URL)。
我的图像返回的URL是这样的:blob:http%3A//localhost%3A4400/705ade8b-5330-4aad-8afa-516d559211a2,这个URL是本地的,因此在刷新浏览器时,url会死亡。我只想从该 url 引用的图像中提取 Base64 编码,因此使用该编码我可以将其插入我的 Sqlite 数据库(我正在使用 Cordova 的相机插件)。

我想从<img>(即(本地/时间))标签中获取 src 并提取 Base64 编码,但我不知道如何操作。任何帮助都会很棒,谢谢。

守则:

应用.js:

  .controller('cameraCtrl', function($scope, Camera) {
    $scope.takePhoto = function() {
      Camera.takePhoto().then(function(urlImage) {
        $scope.lastImage = urlImage;
        //console.log($scope.lastImage);            
      }, function(err) {
        console.err(err);
      }, {
        quality: 50,
        targetWidth: 50,
        targetHeight: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        saveToPhotoAlbum: false
      });
    };
    $scope.savePhoto = function() {
      //This function should get the Base64 encode (Data URL) from the <img/> tag in tab-camera.html
      addImagenCamara(Camara.makeHashBase64ForId(), $scope.lastImage);
    };
    //makeHashBase64ForId is only for the _id field into database, this isn't the image
  });

服务.js:

  .factory('Camera', ['$q',
    function($q) {
      return {
        takePhoto: function(options) {
          var q = $q.defer();
          navigator.camera.getPicture(function(result) {
            q.resolve(result);
          }, function(err) {
            q.reject(err);
          }, options);
          return q.promise;
        },
        makeHashBase64ForId: function() {
          var date = new Date();
          return btoa(date.getTime());
        }
      };
    }
  ]);;

标签相机.html:

<ion-view view-title="Cámara">
  <ion-content>
    <button ng-click="takePhoto()" class="button button-block button-primary">Take photo!</button>
    <button ng-click="savePhoto()" class="button button-block button-primary">Save</button>
    <img src="{{lastImage}}" id="myImage" />//Here goes the (local/temporal) url indeed
  </ion-content>
</ion-view>

您可以使用 Canvas 元素的 toDataURL API 来获取图像的数据 URI (base64),如以下代码片段所示:

function getDataUri(url, cb) {
    var img = new Image();
    img.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth;  // or simply .width
        canvas.height = this.naturalHeight;  // or simply .height
        canvas.getContext('2d').drawImage(this, 0, 0);
        cb(canvas.toDataURL());
    };
    img.src = url;
}
// example of usage
getDataUri('/test.png', function(dataUri) {
    ...
});

PS:如果您的应用程序已经有<image>,则可以编辑函数以直接接收图像对象而不是URL的方式。