【问题标题】:Ionic - save picture to device with a specific filename离子 - 使用特定文件名将图片保存到设备
【发布时间】:2020-09-03 14:51:33
【问题描述】:

我正在开发一个 Ionic/Cordova 应用程序。
我想拍照并将它们保存在我的设备上。我设法做到了,但我真的不知道如何给出一个特定的文件名(而不是有一个 'IMG_20200903...' 文件名)。

我该怎么办?
这是sn-p:

gallery(){

  const options: CameraOptions = {
    quality: 20,
    destinationType: this.camera.DestinationType.FILE_URI,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    saveToPhotoAlbum: true        
  }
  
  this.camera.getPicture(options).then((imageData) => {
   let base64Image = 'data:image/jpeg;base64,' + imageData;
   this.clickedImagePath = imageData;
  }, (err) => {
    alert(err);
  });
}

任何帮助将不胜感激!

【问题讨论】:

    标签: angular cordova ionic-framework camera


    【解决方案1】:
    1. 使用离子电容器:

    您可以使用 ionic FileSystemApi 来编写具有自定义名称的文件。 Ionic FileSystem API

    private async savePicture(cameraPhoto: CameraPhoto) {
      // Convert photo to base64 format, required by Filesystem API to save
      const base64Data = await this.readAsBase64(cameraPhoto);
    
      // Write the file to the data directory
      const fileName = new Date().getTime() + '.jpeg';
      const savedFile = await Filesystem.writeFile({
        path: fileName,
        data: base64Data,
        directory: FilesystemDirectory.Data
      });
    
      // Use webPath to display the new image instead of base64 since it's
      // already loaded into memory
      return {
        filepath: fileName,
        webviewPath: cameraPhoto.webPath
      };
    }
    
    1. 使用 Ionic Native。

    您可以使用Camera & File 插件来编写具有自定义名称的文件。

        //here injecting camera and file class to our component part as object  
        constructor(private camera: Camera, private file: File) {}  
        
        //here this method is used to start a camera and take a picture and save a picture in specific mentioned part.  
        public getPicture() {  
            let base64ImageData;  
            const options: CameraOptions = {  
                //here is the picture quality in range 0-100 default value 50. Optional field  
                quality: 100,  
                /**here is the format of an output file. 
                 *destination type default is FILE_URI. 
                    * DATA_URL: 0 (number) - base64-encoded string,  
                    * FILE_URI: 1 (number)- Return image file URI, 
                    * NATIVE_URI: 2 (number)- Return image native URI        
                    */  
                destinationType: this.camera.DestinationType.DATA_URL,  
                /**here is the returned image file format 
                 *default format is JPEG 
                    * JPEG:0 (number), 
                    * PNG:1 (number), 
                    */  
                encodingType: this.camera.EncodingType.JPEG,  
                /** Only works when Picture Source Type is PHOTOLIBRARY or  SAVEDPHOTOALBUM.  
                 *PICTURE: 0 allow selection of still pictures only. (DEFAULT) 
                    *VIDEO: 1 allow selection of video only.        
                    */  
                mediaType: this.camera.MediaType.PICTURE,  
                /**here set the source of the picture 
                 *Default is CAMERA.  
                    *PHOTOLIBRARY : 0,  
                    *CAMERA : 1,  
                    *SAVEDPHOTOALBUM : 2 
                    */  
                sourceType: this.camera.PictureSourceType.CAMERA  
            }  
            this.camera.getPicture(options).then((imageData) => {  
                //here converting a normal image data to base64 image data.  
                base64ImageData = 'data:image/jpeg;base64,' + imageData;  
                /**here passing three arguments to method 
                *Base64 Data 
    
                *Folder Name 
    
                *File Name 
                */  
                this.writeFile(base64ImageData, “My Picture”, “sample.jpeg”);  
            }, (error) => {  
                console.log('Error Occured: ' + error);       
            });  
        }  
        //here is the method is used to write a file in storage  
        public writeFile(base64Data: any, folderName: string, fileName: any) {  
            let contentType = this.getContentType(base64Data);  
            let DataBlob = this.base64toBlob(base64Data, contentType);  
            // here iam mentioned this line this.file.externalRootDirectory is a native pre-defined file path storage. You can change a file path whatever pre-defined method.  
            let filePath = this.file.externalRootDirectory + folderName;  
            this.file.writeFile(filePath, fileName, DataBlob, contentType).then((success) => {  
                console.log("File Writed Successfully", success);  
            }).catch((err) => {  
                console.log("Error Occured While Writing File", err);  
            })  
        }  
        //here is the method is used to get content type of an bas64 data  
        public getContentType(base64Data: any) {  
            let block = base64Data.split(";");  
            let contentType = block[0].split(":")[1];  
            return contentType;  
        }  
        //here is the method is used to convert base64 data to blob data  
        public base64toBlob(b64Data, contentType) {  
            contentType = contentType || '';  
            sliceSize = 512;  
            let byteCharacters = atob(b64Data);  
            let byteArrays = [];  
            for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {  
                let slice = byteCharacters.slice(offset, offset + sliceSize);  
                let byteNumbers = new Array(slice.length);  
                for (let i = 0; i < slice.length; i++) {  
                    byteNumbers[i] = slice.charCodeAt(i);  
                }  
                var byteArray = new Uint8Array(byteNumbers);  
                byteArrays.push(byteArray);  
            }  
            let blob = new Blob(byteArrays, {  
                type: contentType  
            });  
            return blob;  
        } 
    

    希望这会有所帮助!

    【讨论】:

    • 好的,谢谢,但我猜CameraPhoto 与电容器(@capacitor/core)有关。如何在没有电容器和CameraPhoto 的情况下制作它?
    • 太棒了!我试过了,但let DataBlob = this.base64toBlob(content, contentType); 行有一个错误。错误是cannot find name content
    • 应该是base64Data。
    • 感谢您的编辑。我尝试了代码:相机处于活动状态,拍摄了一张照片,但似乎没有下载到设备中(也许我不知道应该看哪里,但我没有找到它)。
    • 根据代码,检查控制台的成功状态(“文件写入成功”)。如果这可行,请检查您的 externalRootDirectory 是否包含文件夹名称“我的图片”如果存在,那么您的图像将保存在那里。
    猜你喜欢
    • 2018-03-26
    • 2017-06-10
    • 2013-07-22
    • 2013-05-27
    • 1970-01-01
    • 2012-01-23
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多