2017-02-07 4 views
0

Я пытаюсь показать изображение, взятое из камеры или выбранное из галереи, после сохранения изображения в файловой системе, а затем нажимать URL-адрес изображения файла в базу данных sqlite, я не могу найти подходящий способ его отображенияПоказать изображение url от SQLite ionic & cordova

var db = null; 
angular.module('starter', ['ionic', 'ngCordova'])  
    .run(function($ionicPlatform, $cordovaSQLite) {     
     $ionicPlatform.ready(function() {       
      try {         
       db = $cordovaSQLite.openDB({           
        name: "my.db", 
                  location: 'default'         
       });         
       $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS imageTable " + "(id integer primary key, image text)" );       
      } catch (e) {         
       alert(e);       
      } finally {       } 

      if (window.cordova && window.cordova.plugins.Keyboard) { 

       cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 


       cordova.plugins.Keyboard.disableScroll(true); 
      } 
      if (window.StatusBar) { 
       StatusBar.styleDefault(); 
      } 
     }); 
    }) 



    .controller('ImageCtrl', function($scope, $rootScope, $state, $stateParams, $cordovaDevice, $cordovaFile, $ionicActionSheet, $cordovaCamera, $cordovaFile, $cordovaDevice, $ionicPopup, $cordovaActionSheet, $cordovaSQLite, $interval) { 






     $scope.showAlert = function(title, msg) { 
      var alertPopup = $ionicPopup.alert({ 
       title: title, 
       template: msg 
      }); 
     }; 


     $scope.loadImage = function() { 

      var options = { 
       title: 'Select Receipts Image ', 
       buttonLabels: ['Gallery', 'Take photo', 'File System'], 
       addCancelButtonWithLabel: 'Cancel', 
       androidEnableCancelButton: true, 
      }; 
      $cordovaActionSheet.show(options).then(function(btnIndex) { 
       var type = null; 
       if (btnIndex === 1) { 
        type = Camera.PictureSourceType.PHOTOLIBRARY; 
       } else if (btnIndex === 2) { 
        type = Camera.PictureSourceType.CAMERA; 
       } 
       if (type !== null) { 
        $scope.selectPicture(type); 
       } 
      }); 
     } 




     // Take image with the camera or from library and store it inside the app folder 
     // Image will not be saved to users Library. 
     $scope.selectPicture = function(sourceType) { 


      var options = { 
       quality: 75, 
       destinationType: Camera.DestinationType.FILE_URI, 
       sourceType: sourceType, 
       allowEdit: true, 
       encodingType: Camera.EncodingType.JPEG, 
       correctOrientation: true, 
       targetWidth: 800, 
       targetHeight: 800, 
       popoverOptions: CameraPopoverOptions, // for IOS and IPAD 
       saveToPhotoAlbum: false 
      }; 

      $cordovaCamera.getPicture(options).then(function(imagePath) { 
        // Grab the file name of the photo in the temporary directory 
        var currentName = imagePath.replace(/^.*[\\\/]/, ''); 
        // alert(currentName); 

        //Create a new name for the photo to avoid duplication 
        var d = new Date(), 
         n = d.getTime(), 
         newFileName = n + ".jpg"; 
        //alert(newFileName); 
        // If you are trying to load image from the gallery on Android we need special treatment! 
        if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) { 
         window.FilePath.resolveNativePath(imagePath, function(entry) { 
          window.resolveLocalFileSystemURL(entry, success, fail); 

          function fail(e) { 
           console.error('Error: ', e); 
          } 

          function success(fileEntry) { 
           var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1); 
           // Only copy because of access rights 
           $cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success) { 
            // $scope.image = newFileName; 

            $scope.add(newFileName) 




           }, function(error) { 
            $scope.showAlert('Error', error.exception); 
           }); 
           //  alert(fileEntry.nativeURL); 

          }; 
         }); 
        } else { 
         var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1); 
         // Move the file to permanent storage 
         $cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success) { 
          // $scope.image = newFileName; 
          //$scope.images.push(newFileName); 
          $scope.add(newFileName, n) 




         }, function(error) { 
          $scope.showAlert('Error', error.exception); 
         }); 

        } 
       }, 
       function(err) { 
        // Not always an error, maybe cancel was pressed... 
       }) 
     }; 

     $scope.add = function(images) {              
       if (images != null) {           
        $cordovaSQLite.execute(db,"INSERT INTO imageTable (images) VALUES(?)", [images]);         
       }         
       alert("Inserted.");         
       $scope.pathForImage();       
      }, 
      function(e) {         
       alert(e);       
      }; 

     $scope.delete = function(id) {                 
       if (id != '') {$cordovaSQLite.execute(db,"DELETE FROM imageTable WHERE id=?",[id]);   }         
       alert("Deleted.");         
       $scope.ShowAllData();       
      }, 
      function(e) {         
       alert(e);       
      };     

        
     $scope.ShowAllData = function() {       /* SELECT COMMAND */        
      $scope.images = [];       
      $cordovaSQLite.execute(db,"SELECT * FROM imageTable ORDER BY id DESC").then(   function(res) {           
       if (res.rows.length > 0) {             
        for (var i = 0; i < res.rows.length; i++) {  
         $scope.images.push({                 
          id: res.rows.item(i).id, 
          image: res.rows.item(i).images 

                         
         });             
        }           
       }         
      },         function(error) {           
       alert(error);         
      }      ); 

      return $scope.images;      
     }  





     // Returns the local path inside the app for an image 
     $scope.pathForImage = function(image) { 

      return cordova.file.dataDirectory + $scope.ShowAllData(image); 



     }; 

    }); 

HTML

<body ng-app="starter" ng-controller="ImageCtrl"> 
    <ion-pane> 
     <ion-header-bar class="bar-positive"> 
     </ion-header-bar> 
     <ion-content> 
      <img ng-repeat="image in images" ng-src="{{pathForImage(image)}}" style="width: 100%; height: 100%;"> 
     </ion-content> 
     <ion-footer-bar class="bar bar-positive"> 
      <div class="button-bar"> 
       <button class="button icon-left ion-camera" ng-click="loadImage()">Take Photo</button> 
       <button class="button icon-left ion-camera" ng-click="ShowAllData()">show Photo</button> 


      </div> 
     </ion-footer-bar> 
    </ion-pane> 
</body> 

Любая помощь будет оценена,

Благодарности

+0

вы путь сохранения изображения или двоичный файл? –

+0

путь изображения ..... –

+0

что делать, если пользователь удаляет изображение из galary? то как вы это продемонстрируете, я думаю, вы должны преобразовать его в двоичный файл, а затем сохранить и отобразить –

ответ

0

Замените ваш ng-repeat на

<ion-content ng-repeat="image in images" > 
    <img ng-src="{{image.image}}" style="width: 100%; height: 100%;"> 
</ion-content> 
+0

Приятный трюк, но он все еще не отображается , Я думаю, что p roblem находится в $ scope.ShowAllData и pathforImage. –

+0

Можете ли вы создать новое ионное приложение и протестировать его, я разместил здесь весь код, я бы очень его оценил :) –

+0

Да, я мог бы, но вы используете sqlite для этого, мне придется использовать Android-студию. Который у меня нет в Моем ноутбуке. –