Java 以角度 2 将图像转换为 base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42482951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting an image to base64 in angular 2
提问by lakshmi
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.
将图像转换为 angular 2 中的 base64,图像从本地上传。当前正在使用 fileLoadedEvent.target.result。问题是,当我通过 REST 服务将此 base64 字符串发送到 java 时,它无法对其进行解码。当我用免费的在线编码器-解码器尝试这个 base64 字符串时,我也看不到解码的图像。我也尝试使用画布。我没有得到正确的结果。有一件事是确定得到的 base64 字符串不正确,我需要为此添加任何包吗?或者在 angular 2 中是否有任何特定的方式将图像编码为 base64,就像它在 angular 1 - angular-base64-upload 包中一样。
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);
}
}
采纳答案by Parth Ghiya
Working plunkr for base64 String
用于 base64 字符串的工作 plunkr
https://plnkr.co/edit/PFfebmnqH0eQR9I92v0G?p=preview
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));
}
回答by Ben Humphries
Have you tried using btoa or Crypto.js to encode the image to base64 ?
您是否尝试过使用 btoa 或 Crypto.js 将图像编码为 base64 ?
link to cryptojs - https://code.google.com/archive/p/crypto-js/
链接到cryptojs - https://code.google.com/archive/p/crypto-js/
var imgSrcData = window.btoa(fileLoadedEvent.target.result);
var imgSrcData = window.btoa(fileLoadedEvent.target.result);
or
var imgSrcData = CryptoJS.enc.Base64.stringify(fileLoadedEvent.target.result);
或者
var imgSrcData = CryptoJS.enc.Base64.stringify(fileLoadedEvent.target.result);
回答by Ewertom Moraes
another solution thats works for base64 is something like this post https://stackoverflow.com/a/36281449/6420568
另一个适用于 base64 的解决方案类似于这篇文章 https://stackoverflow.com/a/36281449/6420568
in my case, i did
就我而言,我做到了
getImagem(readerEvt, midia){
//console.log('change no input file', readerEvt);
let file = readerEvt.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//console.log('base64 do arquivo',reader.result);
midia.binario = btoa(reader.result);
//console.log('base64 do arquivo codificado',midia.binario);
};
reader.onerror = function (error) {
console.log('Erro ao ler a imagem : ', error);
};
}
and html component
和 html 组件
<input type="file" class="form-control" (change)="getImagem($event, imagem)">
<img class="img-responsive" src="{{imagem.binario | decode64 }}" alt="imagem..." style="width: 200px;"/>
to display the image, i created the pipe decode64
为了显示图像,我创建了管道 decode64
@Pipe({
name: 'decode64'
})
export class Decode64Pipe implements PipeTransform {
transform(value: any, args?: any): any {
let a = '';
if(value){
a = atob(value);
}
return a;
}
}
回答by Johansrk
I modified Parth Ghiya answer a bit, so you can upload 1- many images, and they are all stored in an array as base64 encoded strings
我稍微修改了 Parth Ghiya 的答案,因此您可以上传 1 张图片,并且它们都作为 base64 编码字符串存储在数组中
base64textString = [];
onUploadChange(evt: any) {
const file = evt.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = this.handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
handleReaderLoaded(e) {
this.base64textString.push('data:image/png;base64,' + btoa(e.target.result));
}
HTML file
HTML文件
<input type="file" (change)="onUploadChange($event)" accept=".png, .jpg, .jpeg, .pdf" />
<img *ngFor="let item of base64textString" src={{item}} alt="" id="img">
回答by Sithum Meegahapola
I have a come up with an answer with calling the HTTP request for post method with a json
我想出了一个答案,用 json 调用 post 方法的 HTTP 请求
1.event param is coming from the HTML input tag.
2. self.imagesrc is a component variable to store the data and to use that in the header file we need to cast the "this" to a self variable and use it in the reader. Onload function
3. this.server is the API calling service component variable I used in this component
1.event 参数来自 HTML 输入标签。
2. self.imagesrc 是一个组件变量,用于存储数据并在头文件中使用它,我们需要将“this”转换为 self 变量并在阅读器中使用它。onload函数3.this.server
是我在这个组件中使用的API调用服务组件变量
UploadImages(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
var self = this;
reader.onload = function() {
self.imageSrc = reader.result.toString();
};
var image_data = {
authentication_token: this.UD.getAuth_key ,
fileToUpload: this.imageSrc,
attachable_type: "Photo"
};
this.server.photo_Upload(image_data).subscribe(response => {
if (response["success"]) {
console.log(response);
} else {
console.log(response);
}
});
}
回答by Massimo Variolo
Please consider using this package: image-to-base64
请考虑使用这个包:image-to-base64
Generate a image to base64, you can make this using a path or url.
将图像生成为 base64,您可以使用路径或 url 进行生成。