獲取img的真實寬高


之前項目后台上傳圖片時需要對圖片的寬高做限制,一開始百度了之后使用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;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM