如何在sqlite cordova中保存图像路径 [英] How to save image path in sqlite cordova

查看:97
本文介绍了如何在sqlite cordova中保存图像路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示从相机中拍摄的图像或从图库中选择的图像,将图像保存到文件系统中然后将文件图像url成功推送到sqlite数据库,我找不到显示它的方法,我尝试下面的代码,它只插入到目前为止的img路径

I want show the image taken from camera or chosen from gallery , after saving the image in filesystem then pushing the file image url into sqlite database successfully , I can't find a way to display it ,I tried the code below , it only insert the img path so far

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) {




        var imagesP = [];

        //$scope.images = [];


        $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;
                                    var imgPath = cordova.file.dataDirectory + newFileName;

                                    imagesP.push(imgPath);
                                    $scope.add(imagesP);




                                }, 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);
                            var image = cordova.file.dataDirectory + newFileName;
                            $scope.add(image);




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

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

        $scope.add = function(imagesP) {             
                if (imagesP != null) {          
                    $cordovaSQLite.execute(db, "INSERT INTO imageTable (images) VALUES(?)", [imagesP] );        
                }        
                alert("Inserted.");      
            },
            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 images FROM imageTable").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;    
        } 
        //$scope.ShowAllData();
         
        //$interval($scope.ShowAllData, 2000,1);
               




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

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



        };

    });

HTML

<body ng-app="starter" ng-controller="ImageCtrl">
    <ion-pane>
        <ion-header-bar class="bar-positive">
            <h1 class="title"> Image Upload</h1>
        </ion-header-bar>
        <ion-content ng-repeat="image in images">
            <img ng-src="{{image.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>


推荐答案

您可以通过将destinationType设置为Camera来预览图像。 DestinationType.DATA_URL

you can preview your image by setting destinationType to Camera.DestinationType.DATA_URL

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

在回调中,使用


data:image / jpeg; base64,+ imageData;

"data:image/jpeg;base64," +imageData;

喜欢这个

$cordovaCamera.getPicture(options).then(function(imagePath) {

     var currentImage = "data:image/jpeg;base64," +imagePath;

});

这篇关于如何在sqlite cordova中保存图像路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆