0

I am trying to get and convert my image to Base64 but encoded (free of any special characters that could crush my application). Sadly, the code is not working. I wonder if there is something wrong with the code.

Here is the code:

    $('#button_upload').on('click', function () {
        upload();
    });



    $(":file").on('change', function(){
        loadImage(this);
    });




    function isBase64(str) {
        try {
            return btoa(atob(str)) == str;
        }catch (err) {
            return false;
        }
    }


    function getDataUri(url, callback) {
        var image = new Image();
        image.onload = function (url) {
            var canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
            canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size

            canvas.getContext('2d').drawImage(this, 0, 0);
            callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpg);base64,/, ''));



        };

        image.src = url;

    };

    function loadImage(image) {
        if (image.files && image.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(image.files[0]);
        };
    };

    function imageIsLoaded(e) {
        $('#myImg').attr('src', e.target.result);
    };

    function upload() {

        var src = document.getElementById('myImg').src
        getDataUri(src, function (dataUri) {
            var parameters= {
                picture: dataUri
            };
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

1 Answers1

0

I fixed that in the line:

FROM

callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpg);base64,/, ''));

TO

callback(canvas.toDataURL('image/jpeg').replace(/^data:image\/(png|jpeg);base64,/, ''));

It is String literals, so the regular expression must be EXACTLY equal to the situation.

Pang
  • 9,564
  • 146
  • 81
  • 122