0

I have got base64data from ng-src, but I can't make a jpeg file with this base64data. I have ever been trying as follow: First I have removed the data:image/jpeg:base64, chunk from data:image/jpeg:base64,/9/DEefesdfae453/sdDFEYEUdfdief8fe ... and write this data with test.jpg file by use of $cordovaFile. Here is my code:

        var base64Image = angular.element(document.querySelectorAll('#my-photo')).attr('src');

        var writeData = base64Image.replace(/data:image\/jpeg;base64,/g, '');

        alert(writeData);
        // Writing filtered image -----------------------------------------------------------------

        $cordovaFile.writeFile(ROOT_DIR + PM_DATA_DIR_NAME + '/', $scope.photo.name, writeData, true)
            .then(function (success) {
                // success
                $ionicLoading.hide();
                $ionicPopup.alert({
                    template : "Updated Photo!!"
                });
            }, function (error) {
                // error
                $ionicLoading.hide();
                $ionicPopup.alert({
                    template : "Failed to update Photo!!"
                });
            });

But I can't show the file as image file. It is showing only black screen. (original file size : 19K ---> result file size : 66K)

What's wrong? Please help me. Thank you everybody to help.

Héctor Valverde
  • 1,089
  • 1
  • 14
  • 34
SiYan Xie
  • 179
  • 1
  • 1
  • 9

1 Answers1

1

FileWriter’s write method does not take a base64 string. According to the docs (http://docs.phonegap.com/en/edge/cordova_file_file.md.html#FileWriter) text will be encoded as UTF-8 before being written. So your base64 string is being encoded before writing to the file so it’s not valid image data. You have to pass your image data as a Blob or an ArrayBuffer. Note this only works on iOS and Android. Have a look at Jeremy Banks’ b64toBlob function in this answer: https://stackoverflow.com/a/16245768

function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = 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;
}

You can pass the resulting blob into the write method.

Community
  • 1
  • 1
user2321465
  • 139
  • 6