js中图片二进制和base64的互转

2018-11-27  本文已影响0人  wy若只如初见
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <p>正常图片</p>
        <p></p>
        <img src="132.jpg" />
        <p></p>
        <p>base64</p>
        <p></p>
        <img src="" id="base64" alt="" />
        <p></p>
        <p></p>
        <p>base64转为二进制</p>
        <img src="" id="erjinz" alt="" />
    </body>
    <script src="jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        /**
         * 网络图像文件转Base64
         */
        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
            var dataURL = canvas.toDataURL("image/" + ext);
            return dataURL;
        }

        /**
         *Base64字符串转二进制
         */
        function dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while(n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {
                type: mime
            });
        }

        //**blob to dataURL**
        function blobToDataURL(blob, callback) {
            var a = new FileReader();
            a.onload = function(e) {
                callback(e.target.result);
            }
            a.readAsDataURL(blob);
            return a;
        }
        var result;
        var img = "132.jpg";
        var image = new Image();
        image.src = img;
        image.onload = function() {
            //这样就获取到了文件的Base64字符串
            var base64 = getBase64Image(image);
            $("#base64").attr("src", base64);

            //Base64字符串转二进制
            var file = dataURLtoBlob(base64);

            //二进制转base64
            result = blobToDataURL(file, function(dataurl) {
                console.log(dataurl);
            });

            setTimeout(function() {
                $("#erjinz").attr("src", result.result);
            }, 100);
        }
    </script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读