在ionic2中捕获图像,然后将它们本地存储在手机上

时间:2016-07-21 19:39:53

标签: angular cordova typescript ionic2 ionic3

我使用Cordova Plugin Camera来捕获用户的个人资料图片。我想将其存储在应用程序中。

以下是捕获它的代码:

photodiode

捕获图像后,我想将其存储在本地,以便我可以在配置文件页面上显示它。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您可以使用cordova-plugin-file。我也会改变选项

destinationType : Camera.DestinationType.DATA_URL,

destinationType: Camera.DestinationType.FILE_URI(android)或

destinationType: Camera.DestinationType.NATIVE_URI(ios)

因为DATA_URL可能会占用大量内存并导致应用崩溃或内存不足错误。如果可能,您应该使用FILE_URINATIVE_URI

所以我的想法是抓住设备上图像的路径。有了它,我们可以将该照片移动到为您的应用程序创建的文件夹(这将是永久性的 存储)然后您可以使用该路径在配置文件页面中显示照片。 当我使用这个Cordova插件文件时,它不是Ionic Native 的一部分,所以代码有点难看......

Camera.getPicture(/*...theOptions*/).then(
 (imagePath) => {
     // Create a new file name by using the username or something like that
     let aDate = new Date(),
     aTime = aDate.getTime(),
     userName = this.myCustomUserService.getUserName(),
     newFileName = userName + aTime + ".jpg";

     // Returns a reference to the actual file located at imagePath
     window.resolveLocalFileSystemURL(imagePath,
     (file) => {

         // Returns a reference to the file system
         window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
         (fileSys) => {

             // Gets a reference to your app directory, and if it doesn't exist it creates it
             fileSys.root.getDirectory('yourAppFolderName', {create: true, exclusive: false},
             (directory) => {

                 // Moves the file to that directory, with its new name
                 file.moveTo(directory, newFileName,
                 // The file was succesfully moved and it returns a reference to it. We can use nativeURL to grab the
                 // path to the image on the device
                 (fileEntry) => {
                     this.myCustomUserService.SetProfilePhotoUrl(fileEntry.nativeURL);
                 },

                 // Now we start handing all the errors that could happen
                 (error) => {
                     // The file was unable to be moved
                     // Show error to the user
                     // ...
                 });
             },

             (error) => {
                 // Could not get a reference to your app folder
                 // Show error to the user
                 // ...
             });
         },

         (error) => {
             // Could not get a reference to the file system
             // Show error to the user
             // ...
         });
     });
 },

 (err) => {
      // Could not take picture
      // Show error to the user
      // ...
 });

答案 1 :(得分:0)

您可以使用以下选项:

Camera.getPicture({
    sourceType: 1, // camera
    destinationType: 1, // file uri
    correctOrientation: true,
    saveToPhotoAlbum: true,
    encodingType: 0, // jpeg
}).then((imageUri) => {
});

拍摄的图像将自动保存。然后使用imageUri显示图像。如果您想阅读文件内容,请参阅http://ionicframework.com/docs/v2/native/file/

相关问题