本地与在线图片转Base64及图片预览

查看效果:http://sandbox.runjs.cn/show/tgvbo9nq

 

本地图片转Base64(从而可以预览图片):

function localImgLoad() {
    var src = this.files[0];
    var self = $(this);
    var read = new FileReader();
    read.onload = function(e) {
        var html = "";
        self.parent().append(html);
        document.getElementById('localBase64StrContainer').value = e.target.result;
    }
    read.readAsDataURL(src)
};
        <div>
            本地图片预览(本地图片转Base64):
            <input type="file" onchange="localImgLoad.call(this)"/>
            <br/>
            <textarea id="localBase64StrContainer" cols=50 rows=6>
            textarea>
            <br/>
        div>
        <br/>

 

在线图片转Base64

function convertImgToBase64(url, callback, outputFormat) {
    var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'),
    img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/jpg');
        callback.call(this, dataURL);
        //alert(this);
        canvas = null;
    };
    img.src = url;
}

function onlineButtonGetImg(imgUrl) {
    convertImgToBase64(imgUrl,
    function(base64Img) {
        document.getElementById('onlineBase64StrContainer').value = base64Img;
        $('#onlineBase64StrContainer').parent().append("");
    },'image/png')
}
        <div>
            在线图片转base64:
            <br/>
            <br/>
            <input type="text" id="onlineUrl" size=30 value="http://sandbox.runjs.cn/uploads/rs/61/0dvnfbe3/081408127534068.png"/>
            <button onclick="onlineButtonGetImg(document.getElementById('onlineUrl').value)">
                转换
            button>
            <br/>
            <br/>
            <textarea id="onlineBase64StrContainer"  cols=50 rows=6>
            textarea>
            <br/>
        div>

 

你可能感兴趣的:(git)