Save base64 encoded image to specific filepath

#1

I want to save a base64 encoded .jpg to a specific filepath, how can i solve this?

#2
1 Like
#3

Thanks! I have now created the blob. But im getting ENCODING_ERR when writing

import { File } from '@ionic-native/file';

constructor(public file: File, .....etc

b64toBlob(b64Data, contentType) {
        contentType = contentType || '';
        var sliceSize = 512;
        var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

      var blob = new Blob(byteArrays, {type: contentType});
      return blob;
}

public saveBase64(base64:string, name:string):Promise<string>{
    return new Promise((resolve, reject)=>{
      var realData = base64.split(",")[1]
      let blob=this.b64toBlob(realData, 'image/jpeg')

      this.file.writeFile(this.pictureDir, name, blob)
      .then(()=>{
        resolve(this.pictureDir+name);
      })
      .catch((err)=>{
        console.log('error writing blob')
        reject(err)
      })
    })
  }
#4

Just tested with a .png base64 image, which worked fine. what could trigger it to fail with my .jpg in base64? it displays fine in the page

#5

this.file.writeFile(this.pictureDir, name, blob) in this line what is this.pictureDir ??

#6

I created a folder for the images, so this.pictureDir is the path to that folder

#7

I am quite new to ionic so please excuse my ignorance, but code from above tutorial, where should i insert? I’ve tried inside one of my pages .ts but it says
“Unexpected token, A constructor, method, accessor or property was expected”…

#8

this.writeFile notworking for me please help me