img 轉爲base64

方法一:canvasjavascript

<script type="text/javascript">
    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 dataURL = canvas.toDataURL("image/png");
        return dataURL
        // return dataURL.replace("data:image/png;base64,", "");
    }html


    function main() {
        var img = document.createElement('img');
        img.src = './images/Game of Thrones.jpg';  //此處本身替換本地圖片的地址
        img.onload =function() {
            var data = getBase64Image(img);
            var img1 = document.createElement('img');
            img1.src = data;
            document.body.appendChild(img1);
            console.log(data);
        }
    }
    main()java

</script>canvas

 

方法二:FileReader瀏覽器

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>經過filereader接口讀取文件</title>
    <script type="text/javascript">
        function readAsDataURL()
        {
            if(typeof FileReader=='undifined')          //判斷瀏覽器是否支持filereader
            {
                result.innerHTML="<p>抱歉,你的瀏覽器不支持 FileReader</p>";
                return false;
            }
            var file=document.getElementById("imagefile").files[0];
            if(!/image\/\w+/.test(file.type))           //判斷獲取的是否爲圖片文件
            {
                alert("請確保文件爲圖像文件");
                return false;
            }
            var reader=new FileReader();
            reader.readAsDataURL(file);
            reader.onload=function(e)
            {
                var result=document.getElementById("result");
                result.innerHTML='<img src="'+this.result+'" alt=""/>'
            }app

        }
    </script>
</head>ui

<body>
<p>
    <label>請選擇一個文件:</label>
    <input type="file" id="imagefile" />
    <input type="button" value="讀取圖像" onClick="readAsDataURL();" />
</p>
<div name="result" id="result">
    <!-- 這裏用來顯示圖片結果-->
</div>
</body>
</html>this

 

參考文獻: https://www.cnblogs.com/tugenhua0707/p/4666076.htmlhtm

相關文章
相關標籤/搜索