js下载base64图片
时间: 2024-05-30 18:06:44 浏览: 71
js 图片转base64的方式(两种)
可以使用JavaScript的Blob对象和URL.createObjectURL()方法来实现将base64图片下载到本地。具体实现步骤如下:
1. 将base64图片数据转换为Blob对象。
```
function base64ToBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
```
2. 创建URL对象并使用a标签模拟点击下载链接。
```
function downloadBase64Image(base64Data, fileName) {
var link = document.createElement('a');
link.download = fileName;
link.href = URL.createObjectURL(base64ToBlob(base64Data));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
```
使用示例:
```
downloadBase64Image('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQI12N4+y8BAAD9AAnqFDrcAAAAAElFTkSuQmCC', 'test.png');
```
此方法可将base64格式的图片下载到本地,支持常见的图片格式,如png、jpeg等。
阅读全文