H5 Js圖片轉base64編碼


<!Doctype html>
<html>

<head>
    <meta charset="utf-8" />
    <title>H5 Js圖片轉base64編碼</title>
    <style type="text/css">
        .a{
            border:1px solid #ccc;
        }
        .b{
            border-color:#fff;
        }
        .c{
            float:left;
        }
        .d{
            clear:both;
        }
    </style>
</head>
<body>
<div >
    <span>圖片屬性:</span>
    <span id="info"></span>
</div>
<div class="a c">
    <p>base64編碼:</p>
    <textarea id="base64_code" rows="20" cols="60" class="a b"></textarea>
</div>
<div class="a c" style="width:445px;height:365px;">
    <p>圖片展示:</p>
    <div id="img_area"></div>
</div>

<div class="d">
    <input type="file" id="img_upload" />
</div>
</body>
</html>

<script type="text/javascript">
    window.onload = function() {
        var img_upload = document.getElementById("img_upload");
        var base64_code = document.getElementById("base64_code");
        var img_area = document.getElementById("img_area");
        img_upload.addEventListener('change', readFile, false);
    }

    function readFile() {
        var file = this.files[0];
        if (!/image\/\w+/.test(file.type)) {
            alert("請確保文件為圖像類型");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
            var data = e.target.result;
            var image = new Image();
            image.onload = function() {
                var width = image.width;
                var height = image.height;
                var info = `width=${width},height=${height},size=${file.size}`;
                document.getElementById("info").innerHTML = info;
            }
            image.src = data;
            base64_code.innerHTML = this.result;
            img_area.innerHTML = '<img src="' + this.result + '" alt=""/>';
        }
    }
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM