0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey! Thanks for your quick response! But I am not getting blob in response. I am getting FILE_URI staring with file:/// . How to convert that result in base64? If you can help it will be highly appreciated. Thanks.
I'm not familiar enough with Ionic, it seems to work fine in the browser. I'm going to update my answer with an alternative way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.