html5 image blob读取,javascript - html image blob to base64 - Stack Overflow

A lot of misconception here.

your variable blob is not a Blob, but a string, the url of .file-preview-image.

FileReader can't do anything from this string. (Or at least not what you want).

in the onload callback of the FileReader, you are just checking if the result is equal to an undefined variable dataURI. That won't do anything.

you are trying to console.log the call to readAsDataURL which will be undefined since this method is asynchronous (you have to call console.log in the callback).

But since I guess that what you have is an object url (blob://), then your solution is either to get the real Blob object and pass it to a FileReader, or to draw this image on a canvas, and then call its toDataURL method to get a base64 encoded version.

If you can get the blob :

var dataURI;

var reader = new FileReader();

reader.onload = function(){

// here you'll call what to do with the base64 string result

dataURI = this.result;

console.log(dataURI);

};

reader.readAsDataURL(blob);

otherwise :

var dataURI;

var img = document.querySelector(".file-preview-image");

var canvas = document.createElement('canvas');

canvas.width = img.width;

canvas.height = img.height;

canvas.getContext('2d').drawImage(img, 0,0);

dataURI = canvas.toDataURL();

But note that for the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.

Also, by default, it will convert your image to a png version. You can also pass image/jpegas the first parameter of toDataURL('image/jpeg') if the original image is in JPEG format.

If the image is an svg, then there would be an other solution using the element, but except if you really need it, I'll leave it for an other answer.

JavaScript中的Blob、File和Base64都是处理文件或数据的常用对象。下面将介绍它们的使用场景以及相互之间的转换。 Blob对象用于表示不能被修改的类文件数据,并且可以在被发送到服务器之前进行处理。它可用于在网页上生成和下载文件,比如将网页上的图片存储为Blob对象,然后使用URL.createObjectURL()方法将其显示为图像。此外,Blob对象也可以用于通过XMLHttpRequest或Fetch API将数据发送到服务器。 File对象继承自Blob对象,它是用户在表单中选择的文件的表示形式。File对象可以包含文件的名称、大小、类型以及最后修改日期等信息。在上传文件时,我们通常会使用File对象来获取文件的详细信息并进行验证。 Base64是一种将二进制数据编码为ASCII字符的方式,常用于在文本传输中表示二进制数据。我们可以使用JavaScript的btoa()和atob()函数在Base64字符串和二进制数据之间进行相互转换。 在相互转换方面,可以将Blob对象转换为Base64字符串,然后使用toDataURL()方法将其转换为DataURL,或者使用FileReader对象的readAsDataURL()方法将Blob或File对象转换为DataURL。而将Base64字符串转换为Blob对象,则可以使用Blob构造函数并设置正确的MIME类型。 综上所述,Blob对象适用于处理类文件数据和发送到服务器,File对象适用于处理用户上传的文件,而Base64适用于在文本传输中表示二进制数据。根据具体的应用场景和需求,我们可以进行这三种对象之间的相互转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值