之前项目后台上传图片时需要对图片的宽高做限制,一开始百度了之后使用js进行判断,可是这种方式存在一定问题,后来就改在后台判断了。现在吧这两种方式都贴出来。

一、用js获取:

先说第一个方法:obj.style.width;这个方法,只有在标签里用style属性写进了width的大小,才可以获取到值,否则只返回的为空。看下面的demo:

<img style="width:400px" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">
<script>
var imgW = document.getElementsByTagName('img')[0].style.width;
alert(imgW); //返回值为400px,否则返回空;
</script>

以上这个方法只适应用标签的style属性里添加width值,在引入的样式表中添加width值(不管是link引入还是html页面中使用style标签)也一样获取不到值,返回为空。

然后说一下第二个方法与第三个方法obj.offsetWidth(offsetHeight); obj.clientWidth(clientHeight);一般情况下,如果标签没有设置padding值及border值,那么它们两个获取到的值是一样的。但很多情况下都不是这样的,其实offsetWidth得到的是width值+padding值+border值,clientWidth得到的是width值+padding值,看下面的demo:

<style>
img{ padding:20px;border:1px solid red;}
</style>
<img style="width:400px" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">
<script>
var img = document.getElementsByTagName('img')[0],
imgOffsetWidth = img.offsetWidth, //442px
imgClientWidth = img.clientWidth; //440px;
</script>

注意,现在获取到的img标签的宽,是在img标签里添加的style=”width:400px” 。如果去掉这一属性值,那么上面demo里的imgOffsetWidth与imgClientWidth返回的值就是图片本身的高宽值。可以偿试下。

另处,getComputedStyle 与 currentStyle是处理兼容性的两个方法,获取到的值都是图片在屏幕上显示的仅仅图片的高宽值,不会获取到img标签的padding及border值;但其中getComputedStyle适用于Firefox/IE9/Safari/Chrome/Opera浏览器,currentStyle适用于IE6/7/8。但是如果img标签即使没有设置style属性也没有引入样式表,那么只有getComputedStyle能获取到值,即为图片本身高宽值,currentStyle则返回auto。下面有一个demo:

<img style="width: 400px;" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">

    <script>
function getStyle(el, name) {
if(window.getComputedStyle) {
return window.getComputedStyle(el, null)[name];
}else{
return el.currentStyle[name];
}
}
var div = document.getElementsByTagName('img')[0];
alert(getStyle(div, 'width'));
</script>

可以把img标签里的style属性去掉再测试下。

最后就是obj.naturalWidth(naturalHeight)方法,这是HTML5里新添加的一个获取元素高宽的方法,但只适用于Firefox/IE9/Safari/Chrome/Opera浏览器。下面有一个适用于各个浏览器的demo:

<img style="width: 400px;" src="http://img.hb.aicdn.com/787bf87d05ad774522dd92151b3051b463229a11109598-9QXV9C_fw658">

    <script>
document.addEventListener('DOMContentLoaded',function(){
function getImgNaturalStyle(img,callback) {
var nWidth, nHeight
if (img.naturalWidth) { // 现代浏览器
nWidth = img.naturalWidth
nHeight = img.naturalHeight
} else { // IE6/7/8
var imgae = new Image();
image.src = img.src;
image.onload = function(){
callback(image.width, image.height)
}
}
return [nWidth, nHeight]
}
var img = document.getElementsByTagName('img')[0],
imgNatural = getImgNaturalStyle(img);
alert(imgNatural);
});
</script>

需要注意是的在IE6/7/8浏览器中image.src只有在img图片完全加载出来以后才获取得到,否则会报错。

document.addEventListener("DOMContentLoaded",function(){

       //原因就是当时我们的代码是在这样的环境下写的,这个时候,只是加载了img的标签,即只有DOM结构,图片还没有完全加载进来,所以获取到的值都是0,但如果在window.onloaded的环境下写,就能得到其所示高宽了

}); 

文章参考自:http://www.cnblogs.com/koukouyifan/p/4066564.html

二、将图片上传到后台后进行判断,再将结果返回到前端

  一种是先加载图片到内存,从而获取到图片宽高:

  BufferedImage bufferedImage = ImageIO.read(new File(imagePath));

  int width = bufferedImage.getWidth();

   int height = bufferedImage.getHeight();

  还有一种是不加载整张图片获取图片宽高:  

  File f = new File(upfile.getFilePath());
  // Getting image data from a InputStream
  FileInputStream b;
  b = new FileInputStream(f);
  ImageUtil imageInfo = new ImageUtil(b);

  int imgWidth = imageInfo.getWidth();
  int imgHeight = imageInfo.getHeight();

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
*
* @author 
* 不需要加载整个图片,获取图片的信息
*/
public class ImageUtil {
private int height;
private int width;
private String mimeType;

public ImageUtil(File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
processStream(is);
} finally {
is.close();
}
}

public ImageUtil(InputStream is) throws IOException {
processStream(is);
}

public ImageUtil(byte[] bytes) throws IOException {
InputStream is = new ByteArrayInputStream(bytes);
try {
processStream(is);
} finally {
is.close();
}
}

private void processStream(InputStream is) throws IOException {
int c1 = is.read();
int c2 = is.read();
int c3 = is.read();

mimeType = null;
width = height = -1;

if (c1 == 'G' && c2 == 'I' && c3 == 'F') { // GIF
is.skip(3);
width = readInt(is,2,false);
height = readInt(is,2,false);
mimeType = "image/gif";
} else if (c1 == 0xFF && c2 == 0xD8) { // JPG
while (c3 == 255) {
int marker = is.read();
int len = readInt(is,2,true);
if (marker == 192 || marker == 193 || marker == 194) {
is.skip(1);
height = readInt(is,2,true);
width = readInt(is,2,true);
mimeType = "image/jpeg";
break;
}
is.skip(len - 2);
c3 = is.read();
}
} else if (c1 == 137 && c2 == 80 && c3 == 78) { // PNG
is.skip(15);
width = readInt(is,2,true);
is.skip(2);
height = readInt(is,2,true);
mimeType = "image/png";
} else if (c1 == 66 && c2 == 77) { // BMP
is.skip(15);
width = readInt(is,2,false);
is.skip(2);
height = readInt(is,2,false);
mimeType = "image/bmp";
} else {
int c4 = is.read();
if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) { //TIFF
boolean bigEndian = c1 == 'M';
int ifd = 0;
int entries;
ifd = readInt(is,4,bigEndian);
is.skip(ifd - 8);
entries = readInt(is,2,bigEndian);
for (int i = 1; i <= entries; i++) {
int tag = readInt(is,2,bigEndian);
int fieldType = readInt(is,2,bigEndian);
int valOffset;
if ((fieldType == 3 || fieldType == 8)) {
valOffset = readInt(is,2,bigEndian);
is.skip(2);
} else {
valOffset = readInt(is,4,bigEndian);
}
if (tag == 256) {
width = valOffset;
} else if (tag == 257) {
height = valOffset;
}
if (width != -1 && height != -1) {
mimeType = "image/tiff";
break;
}
}
}
}
if (mimeType == null) {
throw new IOException("Unsupported image type");
}
}

private int readInt(InputStream is, int noOfBytes, boolean bigEndian) throws IOException {
int ret = 0;
int sv = bigEndian ? ((noOfBytes - 1) * 8) : 0;
int cnt = bigEndian ? -8 : 8;
for(int i=0;i<noOfBytes;i++) {
ret |= is.read() << sv;
sv += cnt;
}
return ret;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public String getMimeType() {
return mimeType;
}

public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}

@Override
public String toString() {
return "MIME Type : " + mimeType + "\t Width : " + width
+ "\t Height : " + height;
}
}

获取img的真实宽高的更多相关文章

  1. naturalWidth、naturalHeight来获取图片的真实宽高

    一般在图片放大缩小,或动态插入图片时使用 function imagea(img){ var w = img.naturalWidth; var h = img.naturalHeight; } 注: ...

  2. Android 获取图片真实宽高

    Resources res = mContext.getResources(); BitmapFactory.Options opts = new BitmapFactory.Options(); o ...

  3. 【图像处理】Golang 获取JPG图像的宽高

    一.背景 有些业务需要判断图片的宽高,来做一些图片相关缩放,旋转等基础操作. 但是图片缩放,旋转,拼接等操作需要将图片从 JPG 格式转成 RGBA 格式操作,操作完毕后,再转回 JPG 图片. 那如 ...

  4. js 获取页面可视区域宽高

    获取浏览器窗口的可视区域高度和宽度,滚动条高度有需要的朋友可参考一下. 1.IE中,浏览器显示窗口大小只能以下获取: 代码如下复制代码 代码如下 document.body.offsetWidth d ...

  5. js获取精确的元素宽高(普通获取高度会有误差)

    当js获取元素宽高时, 并不是一个精确的数字,如果想获取真正的宽高大致方法如下 var oStyle = obj.currentStyle ? obj.currentStyle : window.ge ...

  6. Android在onCreate中获取控件的宽高

    在某些需求下,我们需要在onCreate的时候就获取到控件的宽高,但是如果直接用view.getWidth()或view.getHeight()会得到0.这是因为在onCreate执行的时候,控件还没 ...

  7. activity 中获取控件的宽高

    1.第一种方式: TextView textview3 = findViewById(R.id.textview3); textView3.post(new Runnable() { @Overrid ...

  8. 解决获取图片实际尺寸(宽高)的bug

    需求:获取图片的宽高其实是为了预先做好排版样式布局做准备. 可以利用图片onload事件监听获取图片的宽高属性值.在IE9以下版本只能使用图片的width与height属性,HTMl5中新加入了nat ...

  9. js 获取屏幕或元素宽高...

    窗口相对于屏幕顶部距离 window.screenTop 窗口相对于屏幕左边距离 window.screenLeft, 屏幕分辨率的高 window.screen.height, 屏幕分辨率的宽 wi ...

随机推荐

  1. HTML 接收本地文件

    HTML代码请把文件拖到下面的框里触发drop事件读取拖放的文件常用情况:结合XMLHttpRequest和拖放文件实现上传查看和管理本地文件和图片 <!DOCTYPE HTML> < ...

  2. 《PHP中的Math函数》笔记

    ① abs() 绝对值; ② ceil() 向上取整; ③ floor() 向下取整; ④ fmod() 返回除法的浮点数余数; ⑤ getrandmax() 显示随机数最大的可能值; ⑥ is_fi ...

  3. 52. 不用+、-、×、÷做加法[add two numbers without arithmetic]

    [本文链接] http://www.cnblogs.com/hellogiser/p/add-two-numbers-without-arithmetic.html [题目] 写一个函数,求两个整数的 ...

  4. kvm虚拟机静态和动态迁移

    一.kvm虚拟机静态迁移 1.静态迁移就是虚拟机在关机状态下,拷贝虚拟机虚拟磁盘文件与配置文件到目标虚拟主机中,实现的迁移. (1)虚拟主机各自使用本地存储存放虚拟机磁盘文件 本文实现基于本地磁盘存储 ...

  5. ThinkPHP学习总结

    ThinkPHP学习总结 网站开发使用的thinkPHP5.0在此总结备查 MVC关系功能图 一.Thinkphp开发规范 l 类 类库.函数文件统一以.php为后缀: 类的文件名均以命名空间定义,并 ...

  6. Oracle 在线重定义表分区

    ==================原始表================原始表=====================原始表 create table BUILDING_temp(building ...

  7. dubbox rest服务

    1.xml配置: web.xml 定义监听的contextpath,见rest协议定义 <servlet> <servlet-name>dispatcher</servl ...

  8. 最终版的Web(Python实现)

    天啦,要考试了,要期末考试了,今天把最终版的Python搭建Web代码先写这里记下了.详细的过程先不写了. 这次是在前面的基础上重写 HTTPServer 与 BaseHTTPRequestHandl ...

  9. 数据结构与算法之链表-javascript实现

    链表的定义: 链表是一种物理存储单元上非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成.每个结点 ...

  10. 项目中 -- 设置tabBar样式 (旅游局)

    - (void)addChildViewController:(UIViewController *)ViewController image:(UIImage *)image selectImg:( ...