本地与在线图片转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 = "<img src=" + e.target.result + " alt='' />";
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("<img src=" + base64Img + " />");
},'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>
上一篇:C#中鼠标划过按钮时候的提示信息


下一篇:SSH整合时执行hibernate查询报错:java.lang.ClassCastException: com.ch.hibernate.Department_$$_javassist_0 cannot be cast to javassist.util.proxy