Creating a BLOB from a Base64 string in JavaScript

后端 未结 12 2635
说谎
说谎 2020-11-21 04:24

I have Base64-encoded binary data in a string:

const contentType = \'image/png\';
const b64Data = \'iVBORw0KGg         


        
12条回答
  •  清歌不尽
    2020-11-21 04:54

    For image data, I find it simpler to use canvas.toBlob (asynchronous)

    function b64toBlob(b64, onsuccess, onerror) {
        var img = new Image();
    
        img.onerror = onerror;
    
        img.onload = function onload() {
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
    
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    
            canvas.toBlob(onsuccess);
        };
    
        img.src = b64;
    }
    
    var base64Data = 'data:image/jpg;base64,/9j/4AAQSkZJRgABAQA...';
    b64toBlob(base64Data,
        function(blob) {
            var url = window.URL.createObjectURL(blob);
            // do something with url
        }, function(error) {
            // handle error
        });
    

提交回复
热议问题