Losing quality in image when sending to back end

The user uploads a photo which is then edited and cropped using Croppie. The edited and cropped version is the one that needs to be saved in the back end.

The current code takes the edited image, saves it in the database though when fetched, it displays the edited image though it has lost colour/not showing colours (displayed below)

Image being sent:

enter image description here

Image fetched:

enter image description here

And here is the code:

<input id="uploadAvatar" type="file" name="file" accept="image/*" />

$('#uploadAvatar).on('change', function(){

     var reader = new FileReader();
     reader.onload = function (e) { 
          var blob = dataURItoBlob(e.target.result;);
          var fd = new FormData();
          fd.append("file", blob);

          //SERVICE HANDLES THE HTTP REQUEST
          httpUploadAvatarServ('../p3sweb/FileUploadServlet', fd, function (callback) { 
               console.log(callback)
          });
     }  

}

function dataURItoBlob(dataURI) { 

    var binary = atob(dataURI.split(',')[1]); 

    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg '});

}

Question

Why is it that the image is losing quality/colour?

1 answer

  • answered 2019-07-18 15:05 silencedogood

    I think your issue may be in the dataURItoBlob function. Here's how I go about getting the base64 data with croppie before sending it to the server. Tried to abridge my code for simplicity... Hopefully I didn't make it worse:

    function PlaceLargeImg (input, imgId, zindex) {
        var $imgel = $(imgId);
    
        var reader = new FileReader();
        reader.onload = function(e) {
            // Sets preview image src to the value of file input.
            $imgel.attr('src', e.target.result);
    
            // Bind croppie
            cropperlg.bind({
                url: $imgel.attr('src')
            });
            // On click method which crops and sets results to html input.
            $('.btn-crop-lg').on('click', () => {
                cropperlg.result({
                    type: 'canvas',
                    size: {width: 1000, height: 400}
                }).then(function(result) {
                    $('#base64lg').val(result); // Resulting cropped img base64 that gets sent to server.
                    $('#uploadLg').submit(); 
                });
            });
        };
        reader.readAsDataURL(input.files[0]);
    }
    

    EDIT: If your image looks good in a clint-side preview AFTER parsing through dataUritoBlob, then the issue is on the server. In this case, you'll need to post your server side code.