日期:2014-05-16  浏览次数:20375 次

JS加载与获取远程图片
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>JS加载与获取远程图片大小</title>
</head>
<body>
<input id="path" value="http://www.google.cn/intl/zh-CN/images/logo_cn.gif" style="width:400px" /><button onclick="loadpic($('prev'),$('path').value)">加载</button><button onclick="getImgSize($('path').value);">获取大小</button>
<div id="prev"></div>
<script type="text/javascript">
var $=function(id){
	return document.getElementById(id);
}
function loadpic(holder,url){
	holder.innerHTML='正在加载...';
	var img=new Image();
	img.src=url;
	var imgElem=document.createElement('img');
	var dick=setInterval(function(){
		if(img.complete){
			clearInterval(dick);
			holder.innerHTML='';
			imgElem.src=img.src;
			img=null;
			holder.appendChild(imgElem);
			return imgElem;
		}
	},50);
}
function getImgSize(url){
	var img=new Image();
	img.src=url;
	var imgElem=document.createElement('img');
	var dick=setInterval(function(){
		if(img.complete){
			clearInterval(dick);
			imgElem.src=img.src;
			img=null;
			document.body.appendChild(imgElem);
			imgElem.style.visibility='hidden';
			alert('图片宽度:'+imgElem.offsetWidth+'\r\n图片高度:'+imgElem.offsetHeight);
			document.body.removeChild(imgElem);
		}
	},50);
}
</script>
</body>
</html>

?

?

另一种方法:

HTML代码:

<span id="span">hello world</span>

?

JS代码:

var span=document.getElementById("span");
var imgEle=document.createElement("img");
span.innerHTML="图片加载中……";
var url="http://www.gdstc.gov.cn/msg/image/zwxw/201007/20100723hzc07.jpg";
function loadImage(url, callback) {
??? var img = new Image(); //创建一个Image对象,实现图片的预下载
???? img.src = url;
??
??? if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数
???????? callback.call(img);
??????? return; // 直接返回,不用再处理onload事件
???? }

???? img.onload = function () { //图片下载完毕时异步调用callback函数。
???
???????? callback.call(img);//将回调函数的this替换为Image对象
???? };
};
function imgLoaded(){
?? alert(this.width);
??? span.innerHTML="";
??? ?imgEle.src=this.src;
??? ?span.appendChild(imgEle);
}
loadImage(url,imgLoaded);