I have just inherited some code which loads an image locally, displays it and creates a byte array (with the intention of later uploading it). The code is the following:

       $scope.uploadFile = function (input) {
           if (input.files && input.files[0]) {
               var reader = new FileReader();
               $scope.inputID = input.id;
               reader.onload = $scope.imageIsLoaded;
               $scope.imageName = input.files[0].name;
               reader.readAsDataURL(input.files[0]);
           }
       };
       $scope.imageIsLoaded = function (e) {
           $scope.$apply(function () {
               var index = parseInt($scope.inputID.substring('photo-upload'.length));
               $('#imagenSeleccionada' + index).attr('src', e.target.result);

               //Create a canvas and draw image on Client Side to get the byte[] equivalent
               var canvas = document.createElement("canvas");
               var imageElement = document.createElement("img");

               imageElement.setAttribute('src', e.target.result);
               canvas.width = imageElement.width;
               canvas.height = imageElement.height;
               var context = canvas.getContext("2d");
               context.drawImage(imageElement, 0, 0);
               var base64Image = canvas.toDataURL("image/jpeg");

               $scope.materiales[index].Imagen = base64Image.replace(/data:image\/jpeg;base64,/g, '');
               $scope.materiales[index].NombreImagen = $scope.imageName;
               $scope.imageName = null;
           });
       }

This code works almost fine in Firefox and Microsoft Edge, but not in Chrome. In Chrome, imageElement.width and imageElement.height are both 0, so then, when doing canvas.toDataURL("image/jpg"), it returns "data:," instead of returning the byte array.

Is this a known issue? Is the code wrong?

0 Answers