在javascript中将Base64转换为图像

时间:2022-12-02 21:19:39
<script type="text/javascript">
    window.onload = function() {
        var options =
        {
            imageBox: '.imageBox',
            thumbBox: '.thumbBox',
            spinner: '.spinner',
            imgSrc: 'avatar.png'
        }
        var cropper = new cropbox(options);
        document.querySelector('#file').addEventListener('change', function(){
            var reader = new FileReader();
            reader.onload = function(e) {
                options.imgSrc = e.target.result;
                cropper = new cropbox(options);
            }
            reader.readAsDataURL(this.files[0]);
            this.files = [];
        })
        document.querySelector('#btnCrop').addEventListener('click', function(){
            var img = cropper.getDataURL();            
            document.querySelector('.cropped').innerHTML += '<img src="'+img+'">';
        })
        document.querySelector('#btnZoomIn').addEventListener('click', function(){
            cropper.zoomIn();
        })
        document.querySelector('#btnZoomOut').addEventListener('click', function(){
            cropper.zoomOut();
        })



    };
</script>

I downloaded an image cropping tool and it working fine . but it returns a Base64. I want that to be saved as a image file in the local drive. Help me with the code . Thanks in advance :)

我下载了一个图像裁剪工具,它工作正常。但它返回一个Base64。我希望将其保存为本地驱动器中的图像文件。帮我处理代码。提前致谢 :)

1 个解决方案

#1


0  

try this code for rendering a base64 data (say base64_string) into an image

尝试使用此代码将base64数据(例如base64_string)渲染到图像中

var html = "<img src='data:image/png;base64," + base64_string + "'>";
document.body.appendChild( html );

also you need to put this code in the onload event of the reader api

您还需要将此代码放在reader api的onload事件中

reader.onload = function(event) {
       var html = "<img src='data:image/png;base64," + event.target.result + "'>";
       document.body.appendChild( html );
   };

#1


0  

try this code for rendering a base64 data (say base64_string) into an image

尝试使用此代码将base64数据(例如base64_string)渲染到图像中

var html = "<img src='data:image/png;base64," + base64_string + "'>";
document.body.appendChild( html );

also you need to put this code in the onload event of the reader api

您还需要将此代码放在reader api的onload事件中

reader.onload = function(event) {
       var html = "<img src='data:image/png;base64," + event.target.result + "'>";
       document.body.appendChild( html );
   };