Search code examples
filewebviewtitaniumbase64

Writin base64encoded image to file in titanium


Question is how to get the image data in standart base64 type written from a webview to a file (jpeg in my case) on external storage?

Ti.App.addEventListener('app:save_op', function(d) { //listens events fired from js in webview

                        var base64img = d.url;
                        var imageBlob = Ti.Utils.base64decode(base64img);


                        var imageView = Titanium.UI.createImageView({
                            image:imageBlob,
                            // top:20,
                            // width:300,
                            // height:100
                        });

                        self.add(imageView);


                        if (Ti.Filesystem.isExternalStoragePresent()) {

                            // var theMap = win1.toImage();
                              // var file = Titanium.Filesystem.createTempFile(Titanium.Filesystem.resourcesDirectory);
                              // Ti.API.info('size = ' + file.size);
                              // file.write(theMap);



                            fname = new Date().getTime() + '_' + 'out.jpg';
                            fname2 = new Date().getTime() + '_' + 'o.jpg';

                            var f = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, fname);
                            var f2 =Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, fname2);
                            // f2 = f.read();
                            // f2.write();

                            f.write(d.url);
                            //
                            //f.write( imageBlob );

                            // var img = new Image();
                            // img.src = imageBlob; 

                            f.write(imageView.image);
                            alert("nativePath = " + f.nativePath);

I implement event listener to catch base64 string of jpeg file from fireevent in a webview then....but it only writes them as plaintext to a file, not an image } I have tried a lot of varients to do this: toImage/ blob--->buffer --->file / base64decode.toString....


Solution

  • If you are only trying to save image to the device, you can try :

    Titanium.Media.saveToPhotoGallery(imageBlob);
    

    Here is the documentation