JS预览上传图片

//图片读取时设置宽度
function showImgFromFile(file,showImgName,maxLength,maxSize)
{
if (_this!=null)
{
  _this=null;
}
var _this=this;
this.imgType=".jpg|.gif|.bmp|.jpeg|.png|.tif";
this.img=null;
this.img=new Image();
this.file=file;
this.showImgName=showImgName;
this.width=maxLength;
this.maxSize=maxSize;

this.show=function()
{
  //判断格式
  var thisExe=_this.file.value.substr(_this.file.value.lastIndexOf(".")).toLowerCase();
     if (_this.imgType.indexOf(thisExe)==-1)
     {
        alert("请选择合适的图片格式,如: jpg,gif,bmp。");
        return false;
     }
  _this.img.onreadystatechange=_this.showImg;
  _this.onerror=_this.error;
  _this.img.src=_this.file.value;
}
this.showImg=function()
{
  if (_this.img.readyState=="complete")
  {
   //判断文件大小
   var tmpFileSize=_this.img.fileSize;
   if (parseInt(tmpFileSize)/1024>_this.maxSize)
   {
    alert("图片文件大小不能超出" + _this.maxSize.toString() + "K");
    return false;
   }
   var showImgControl=document.getElementById(_this.showImgName);
   showImgControl.src=_this.img.src;
   showImgControl.style.display="block";
  
   //下面判断长高
   var tmpWidth=_this.img.width;
   var tmpHeight=_this.img.height;
   var showWidth;
   var showHeight;
   if (tmpWidth > tmpHeight)
   {
    if (tmpWidth>_this.width)
    {
     showWidth=_this.width;
     showHeight=(tmpHeight*showWidth)/tmpWidth;
    }
    else
    {
     showWidth = tmpWidth;
     showHeight=(tmpHeight*showWidth)/tmpWidth;
    }
   }
   else
   {
    if (tmpHeight > _this.width)
    {
     showHeight = _this.width;
     showWidth = (tmpWidth*showHeight)/tmpHeight;
    }
    else
    {
     showHeight = tmpHeight;
     showWidth = (tmpWidth*showHeight)/tmpHeight;
    }
   }
   //下面调整长度
   showImgControl.style.width = showWidth;
   showImgControl.style.height = showHeight;
  }
}
this.error=function()
{
  alert("请选择合适的图片格式,如: jpg,gif,bmp。");
}
}
function showUploadImg(file,showImgName,maxMidth,maxSize)
{
var s=new showImgFromFile(file,showImgName,maxMidth,maxSize);
s.show();
}
posted @ 2009-11-05 17:03  Silver.Lee  阅读(1314)  评论(0编辑  收藏  举报