Convert Image FILE_URI into Base64 string?

I need to convert File Uri response from Image picker into base64 string.

I have tried file reader for converting the file uri into base64 but it is not working.

const options: ImagePickerOptions = {
      maximumImagesCount: 1,
      width: 1200,
      height: 1200,
      quality: 80
    };

    this.imagePicker.getPictures(options).then(async (results) => {
      const fileData: string = results[0];
            const path: string = fileData.substring(0, fileData.lastIndexOf('/') + 1);
            const fileName: string = fileData.split('/').pop();

            console.log(fileName, "fileName");
            console.log(path, "Path");

            this.file.readAsDataURL(path, fileName)
              .then((base64File) => {
                console.log("here is encoded image ", base64File)
              })
              .catch((err) => {
                console.log('Error reading file', err);
              })
});

Please let me know where I am going wrong.Any suggestion or solution is appreciated. Thanks in advance.

Upvotes: 0

Views: 435

Answers (1)

Yannick Beauchamp-H
Yannick Beauchamp-H

Reputation: 1671

You can set the outputType in ImagePickerOptions to window.imagePicker.OutputType.BASE64_STRING, then results should be an array of base64 string. But you won't be able to get the file name the way you did.

const options: ImagePickerOptions = {
  maximumImagesCount: 1,
  width: 1200,
  height: 1200,
  quality: 80,
  outputType: window.imagePicker.OutputType.BASE64_STRING
};

this.imagePicker.getPictures(options).then(async (results) => {
  const base64File: string = results[0];
  console.log("here is encoded image ", base64File);
});

You might have to cast window as any.

Upvotes: 1

Related Questions