Saturday, January 28, 2012

Image Upload control in JavaScript

JavaScript Code:
<script language="javascript" type="text/javascript">
        var maxWidth=75;
        var maxHeight=20;
        var fileTypes = ["gif", "png", "jpg", "bmp", "jpeg"];
        var outImage="previewField";
        var defaultPic = "Sunset.gif";

        function preview(what){
          var sourcefile=what.value;
          var ext = sourcefile.substring(sourcefile.lastIndexOf(".") + 1, sourcefile.length).toLowerCase();
          for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
          globalPic=new Image();
          if (i < fileTypes.length) {
              globalPic.src = sourcefile;
              alert("This is valid image!");
          }
          else {
              globalPic.src = defaultPic;
              alert("That is not avalid image!");
          }
          setTimeout("applyChanged()",500);
        }

        var globalPic;
        function applyChanged(){
          var field=document.getElementById(outImage);
          var x=parseInt(globalPic.width);
          var y=parseInt(globalPic.height);
          if (x>maxWidth) {
            y*=maxWidth/x;
            x=maxWidth;
          }
          if (y>maxHeight) {
            x*=maxHeight/y;
            y=maxHeight;
          }
          field.style.display=(x<1 || y<1)?"none":"";
          field.src=globalPic.src;
          field.width=x;
          field.height=y;
}
</script>

HTML Code:
<input type="file" id="imageField" onchange="preview(this)">
 
 

No comments: