VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > JavaScript教程 >
  • JavaScript—图片与base64编码互相转换

图片转换为base64编码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<input type = "file"  id = "file" onchange="popFileName(this)" multiple = "multiple" name="点我上传"/>
<div id="imgContainer"></div>
<script src="C:\Users\bt.cn\Desktop\jquery-3.3.1.min.js"></script>
<script>
    function popFileName(that) {
        var path1 = document.getElementById("file").value;
        console.log(path1);                         // C:\fakepath\ddd.jpg,这不是真实路径
        var path2 = document.getElementById("file").files[0];
        var objURL = getObjectURL(that.files[0]);   // 这里的objURL就是input file的真实路径
        
        var image = new Image(); 
        image.src = objURL; 
        image.onload = function(){ 
            var base64 = getBase64Image(image); 
            console.log(base64); 
            $('#imgContainer').html("<img src='" + objURL + "' width='"+image.width+"' height='"+image.height+"' id='target'/>");
        
    }
    
    // 获取上传图片文件的真实路径
    function getObjectURL(file) {
        var url = null;
        if (window.createObjcectURL != undefined) {
            url = window.createOjcectURL(file);
        else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
    
    // 得到上传图片文件的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); 
        var dataURL = canvas.toDataURL("image/jpeg");
        return dataURL; 
    
</script>

相关教程