擷取img的真實寬高

來源:互聯網
上載者:User

標籤:環境   dom   boolean   event   over   chrome   rip   public   alert   

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.