Base64图片转成URL地址

前端
1536 0

后台接口返回的是BASE64编码的图片字符串,前端可以直接在<img src=''>中放入整个编码内容。

还有一种方式,就是转为一个简短的本地链接,如blob:http://127.0.0.1/76da5fcc-01b1-4dcd-a95f-c6927ca66b4f。方法如下:

/**
 * @brief 将base64编码的图片,转成URL地址
 *
 * @example 'blob:http://127.0.0.1/76da5fcc-01b1-4dcd-a95f-c6927ca66b4f'
 */
function imgBase64ToUrl(base64) {
    try {
        // 去除base64的前缀,有的话则解析出图片格式
        let mimeType = 'image/png';
        if (base64.indexOf('data:image') >= 0) {
            let arr = base64.split(',')
            mimeType = arr[0].match(/:(.*?);/)[1] || 'image/png';
            base64 = arr[1];
        }
        let bytes = window.atob(base64);
        
        // 处理异常,将ascii码小于0的转换为大于0
        let ab = new ArrayBuffer(bytes.length);
        let ia = new Uint8Array(ab);
        for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        // 构造blob
        let blob = new Blob([ab], {
            type: mimeType
        });
        // 构造URL
        let url = URL.createObjectURL(blob);
        return url;
    }
    catch (e) {
        console.log(e);
        return '';
    }
}

使用示例:

// base64编码的图片内容
let base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAABACAIAAABdtOgoAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAG5SURBVHhe7dxBbsJQEIPh0Mu0tyzH5DZpwFlUKgX6MjO2X+cXErDEXwiwIKd1XZeO19t+35FqAHKn9fN9f9jVd77cAM6X/XlX2fljW75PQeQagJwbwPVte7vNkhXA991nMfAB+Ln4FAYmAL9t7W/gAPB4ZXMDeYBX9nU20Aa4u+zdn422BsIAD9afyEAV4OmxP4uBJMDT9dEUBnoAL66P/A3EAP60PjI3UAIYWB85G8gADK+PbA00AA6ujzwNBABC1keGBmyAwPWRmwEVIHx9ZGXAA0haH/kYkABS10cmBgyAgvWRg0E5QNn6SN6gFqB4faRtUAhAWR8JG1QBENdHqgYlAPT1kaRBPoDI+kjPIBlAan0kZpAJILg+UjJIA5BdH8kY5ACIr480DBIALNZHAgbRAEbrI7ZBKIDd+ohqEAdguj7iGQQBWK+PSAYRABOsjxgGhwGmWR+VGxwDmGx9VGtw4J/yye9NxWKPrW3A8X/K/8P1txJeddC3oG60BiA3fAoy/6QdK+FV9+VqeB36EO6CagByDUCuAcg1ALkGINcA5BqAXF+4ldr1wq198W5qfQoi1wDUluULGemslZjN3tgAAAAASUVORK5CYII=';

let url = imgBase64ToUrl(base64);
console.log(url);

let imgElem = document.createElement('img');
imgElem.src = url;
imgElem.style = 'position: fixed; left: 50%; top: 50vh; z-index: 9999';
document.body.appendChild(imgElem);
// 执行上面的代码,屏幕正中心将出现一张图片
最后更新 2023-06-12
评论 ( 0 )
OωO
隐私评论