将字节数组转换为图片无法在Chrome中运行

时间:2019-04-25 16:03:05

标签: javascript angularjs html5 google-chrome

我刚刚继承了一些代码,可以在本地加载图像,显示图像并创建字节数组(以供以后上传)。 代码如下:

       $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;
           });
       }

此代码在Firefox和Microsoft Edge中几乎可以正常工作,但在Chrome中则不能。在Chrome中,imageElement.widthimageElement.height均为0,因此,当执行canvas.toDataURL("image/jpg")时,它返回"data:,"而不是返回字节数组。

这是一个已知问题吗?代码是否错误?

0 个答案:

没有答案