简体   繁体   English

将Base64转换为JavaScript中的图像

[英]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. 但它返回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 尝试使用此代码将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 );
   };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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