页面上的应用大多都有在我的信息管理中设置头像的这么一个功能,而对于实现这个功能前提就是上传头像的功能,而当上传完成便可预览是全部后续操做的前提。在网上巴拉了一番,而后整理了一下,拼凑了一个小demo供你们学习。本博文出自博客园,做者Red,联系邮箱 it_red@sina.com,转载请保留本文原文连接http://www.cnblogs.com/itred/p/5723864.html。javascript
这个demo基本能够实现页面上打开页面后,点击上传头像图片的按钮,通过选择,上传成功后便可在页面指定位置显示刚刚确认上传完成的图片,这个图片的大小是通过默认设置的,对于页面的样式,图片的大小等这些均可以根据本身的实际应用进行调整,最重要的是这个功能基本可用,并且兼容多个浏览器,不会出现浏览器不兼容的问题,若是还有浏览器没有测出来,请各位指出,以便进一步优化,在此表示感谢。css
说一下开发环境,我用的是idea完成的,可是这个demo并不依赖开发环境,实际上就是一个html和一张默认的图片,其实就是最基础的js实现的。所以通常人均可以看懂,并且还能够进一步进行扩展。html
1.style样式设置:java
<title>图片上传本地预览</title> <style type="text/css"> #preview{ width: 180px; height: 183px; border: 1px solid gray; overflow: hidden; } #imghead{ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image); } </style>
2. 核心javascript:git
<script type="text/javascript"> function previewImage(file) { var MAXWIDTH = 180; var MAXHEIGHT = 180; var div = document.getElementById('preview'); if (file.files && file.files[0]) { div.innerHTML = '<img id=imghead>'; var img = document.getElementById('imghead'); img.onload = function () { var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight); img.width = rect.width; img.height = rect.height; img.style.marginLeft = rect.left+'px'; img.style.marginTop = rect.top + 'px'; } var reader = new FileReader(); reader.onload = function (evt) { img.src = evt.target.result; } reader.readAsDataURL(file.files[0]); }else{ //兼容IE var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'; file.select(); var src = document.selection.createRange().text; div.innerHTML = '<img id=imghead>'; var img = document.getElementById('imghead'); img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src; var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight); status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height); div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sFilter+src+"\"'></div>"; } } function clacImgZoomParam( maxWidth, maxHeight, width, height ){ var param = {top:0, left:0, width:width, height:height}; if( width>maxWidth || height>maxHeight ){ rateWidth = width / maxWidth; rateHeight = height / maxHeight; if( rateWidth > rateHeight ){ param.width = maxWidth; param.height = Math.round(height / rateWidth); }else{ param.width = Math.round(width / rateHeight); param.height = maxHeight; } } param.left = Math.round((maxWidth - param.width) / 2); param.top = Math.round((maxHeight - param.height) / 2); return param; } </script>
3. body布局以下:github
<body> <div id="preview"> <img id="imghead" border=0 src="img/head_180.jpg" width="180" height="180" /> </div> <input type="file" onchange="previewImage(this)" /> </body>
基本就是完成了。demo的源码下载请点击我,运行效果以下:浏览器
做者:Red 博客:http://itred.cnblogs.com
GitHub:https://github.com/itRed ide
版权声明:本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段说明,
且在文章明显位置给出原文连接,不然保留追究法律责任的权利。布局