简体   繁体   中英

Convert a Base64 into an image in javascript

<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 :)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM