Search code examples
javascripttype-conversionbase64tiff

Convert a base64 string encoded image to a tiff format in javascript


I have a base64 image that I need to convert into a .tiff format. Is there a (pure) javascript way to do it please ?

NB : I saw base64 encoding was just a compress of the original file, I did this to recover the original file but now have to transform it to tiff

function urltoFile(url, filename, mimeType){
    mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename, {type:mimeType});})
    );
}

Solution

  • The framework I use (CEP) allow to convert local file into tiff format using this code :

    //save the file in tiff format in a specified fodler
    csInterface.evalScript(`exportFile()`, function(path) {
         console.log("saved at",path);
    });
    
    //in jsx 
    function exportFile() {
        Folder((fnp = (aD = activeDocument).fullName.parent + '/folder/')).create();
        aD.saveAs(File(fnp + aD.name), new TiffSaveOptions(), true, Extension.LOWERCASE);
        return activeDocument.fullName;
    }
    
    
    //then u can get it with this code
     csInterface.evalScript('app.documents[0].fullName.fsName', function(res) {
          //give the location of the current document
          let path = res;
          path  = res.substring(0, res.lastIndexOf("\\"));
          let fileName = res.substring(res.lastIndexOf("\\"));
          fileName = fileName.substr(1, fileName.lastIndexOf(".")) + "tif";
          path += "\\folder\\" + fileName;
          console.log(path);
    
          let fileInBase64 = window.cep.fs.readFile(path, cep.encoding.Base64);
          //transform the path to match the tif file
          //let fileName =  res.split('\\').pop().split('/').pop();
          urltoFile('data:image/png;base64,'+fileInBase64.data, fileName)
          .then(function(file){
            console.log(file);
          });
    });