Click on the base64 encoded image to display it on another page

The starting code is like this. A new window is opened to display the base64-encoded image, but the URL is too long and the display fails.

openImage(imgSrc) {
    window.open(imgSrc, '_blank');
},

Solution: This code takes a Base64 encoded image data and converts it into a Blob object.

Blob: is a special URL scheme used to represent a reference to a Blob object or File object in browser memory.

Note: blob URLs are ephemeral. When they are no longer referenced, or when you call the URL.revokeObjectURL() method, they are released to reduce memory usage. This means that blob URLs are not persistent, they only exist within the current browser session. If you open a blob URL in a new browser window or tab, it won't work because the URL is specific to the previous browser context.

Here is the code:

openImage(base64Data) { 
    // 解码base64编码的数据。base64Data.split(',')[1]是提取真正的图像数据(移除了"data:image/jpeg;base64,"部分)
    const byteCharacters = atob(base64Data.split(',')[1]);

    // 创建一个数组,用于存储每个字符的ASCII码
    const byteNumbers = new Array(byteCharacters.length);

    // 遍历byteCharacters字符串,并将每个字符的ASCII码值存储在byteNumbers数组中
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }

    // 使用byteNumbers数组创建一个Uint8Array对象。Uint8Array是一个字节的数组。
    const byteArray = new Uint8Array(byteNumbers);

    // 用byteArray创建一个Blob对象。Blob对象代表一个不可变、原始数据的类文件对象。
    // Blob对象的内容是由选项type指定的MIME类型。
    const blob = new Blob([byteArray], {type: 'image/jpeg'});

    // 创建一个指向存储在Blob对象中的数据的URL。这个URL可以用于文件下载或者用在img标签的src属性中。
    const imageUrl = URL.createObjectURL(blob);

    // 在新的浏览器窗口或标签页中打开上面创建的URL,从而显示该图像
    window.open(imageUrl, '_blank');
}

 

over.

Guess you like

Origin blog.csdn.net/LYXlyxll/article/details/132289216