将图像转换为角度2中的base64 [英] Converting an image to base64 in angular 2

查看:81
本文介绍了将图像转换为角度2中的base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将图像转换为角度2的base64,图像从local上传.当前正在使用fileLoadedEvent.target.result.问题是,当我通过REST服务将此base64字符串发送给java时,它无法对其进行解码.当我尝试使用带有免费在线编码器-解码器的base64字符串时,也看不到解码图像.我也尝试使用画布.没有得到正确的结果.一件事肯定所得到的base64字符串不合适,我是否需要为此添加任何软件包?或者在angular 2中,有什么垂直方式可以将图像编码为base64,就像在angular 1中一样-angular-base64-upload包.

Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 - angular-base64-upload package.

请在下面的示例代码中找到

Pls find below my sample code

onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
    var filesSelected = imgLogoUpload.files;
    var self = this;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0]; 

      //Reading Image file, encode and display
       var  reader: FileReader = new FileReader();
       reader.onloadend = function(fileLoadedEvent:any) {

       //SECOND METHO
       var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64 

        var newImage = imageForLogo;
        newImage.src = imgSrcData;
        imageDiv.innerHTML = newImage.outerHTML;

      }
      reader.readAsDataURL(fileToLoad);
    }
}

推荐答案

为base64字符串使用plunkr

Working plunkr for base64 String

https://plnkr.co/edit/PFfebmnqH0eQR9I92v0G?p=preview

  handleFileSelect(evt){
      var files = evt.target.files;
      var file = files[0];

    if (files && file) {
        var reader = new FileReader();

        reader.onload =this._handleReaderLoaded.bind(this);

        reader.readAsBinaryString(file);
    }
  }



  _handleReaderLoaded(readerEvt) {
     var binaryString = readerEvt.target.result;
            this.base64textString= btoa(binaryString);
            console.log(btoa(binaryString));
    }

这篇关于将图像转换为角度2中的base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆