Get the true width and height of img

Source: Internet
Author: User

Before the project background upload pictures need to limit the width of the picture, the beginning of Baidu after the use of JS to judge, but this way there are certain problems, and then changed in the background to judge. Now, both of these methods are posted.

First, use JS to obtain:

First of all: Obj.style.width; This method, only in the label with the style attribute is written in the width of the size, you can get to the value, otherwise only return is empty. Look at the demo below:

<script>var IMGW = document.getElementsByTagName (' img ') [0].style.width;   alert (IMGW);  Returns a value of 400px, otherwise returns an empty;</script>

This method only adapts to adding the width value in the style attribute of the label, and adding the width value in the introduced style sheet (either link introduction or the use of the style tag in the HTML page) also gets a value that is not returned as null.

Then say a second method and a third method Obj.offsetwidth (offsetheight); Obj.clientwidth (clientheight); In general, if the label does not have padding values and border values set, then the two values they get are the same. But in many cases is not the case, in fact offsetwidth get is the width value +padding value +border value, clientwidth get the Width value +padding value, see the following demo:

<style>img{padding:20px;border:1px solid Red;} </style><script>var img = document.getElementsByTagName (' img ') [0],             imgoffsetwidth = img.offsetwidth,  //442px            imgclientwidth = Img.clientwidth;  440px;</script>

Note that now gets to the width of the IMG tag, which is added in the img tag style= "width:400px". If this attribute value is removed, then the value returned by the Imgoffsetwidth and Imgclientwidth in the demo above is the height-width value of the image itself. can be tested.

Also, getComputedStyle and Currentstyle are two ways to deal with compatibility, and the values obtained are the only high-width values of the pictures displayed on the screen, not the padding and border values of the IMG tags. But the getComputedStyle applies to the Firefox/ie9/safari/chrome/opera browser, Currentstyle applies to IE6/7/8. However, if the IMG tag does not have a style sheet, even if it is not set, then only getComputedStyle can get the value, which is the height of the picture itself, and Currentstyle returns auto. Here's a demo:

    <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>

You can remove the style attribute from the IMG tag and test it again.

The last is the Obj.naturalwidth (Naturalheight) method, which is a newly added method in HTML5 that gets the height of the element, but only applies to the Firefox/ie9/safari/chrome/opera browser. Here's a demo for each browser:

    <script>        document.addeventlistener (' domcontentloaded ', function () {            function Getimgnaturalstyle (img,callback) {                var nwidth, nheight                if (img.naturalwidth) {//modern browser                    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>

It is important to note that in the Ie6/7/8 browser image.src is only obtained after the IMG image is fully loaded, otherwise it will be an error.

Document.addeventlistener ("domcontentloaded", function () {       

Article reference from: http://www.cnblogs.com/koukouyifan/p/4066564.html

Second, the image is uploaded to the background after the judgment, and then return the results to the front

One is to load the image into memory first, thus getting to the picture width height:

BufferedImage bufferedimage = Imageio.read (new File (ImagePath));

  int width = bufferedimage.getwidth ();

int height = bufferedimage.getheight ();

Another way is not to load the entire picture to get the picture width:  

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
* No need to load whole picture, get information of picture
*/
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 = = && C3 = =) {//PNG
Is.skip (15);
width = readInt (is,2,true);
Is.skip (2);
Height = readInt (is,2,true);
MimeType = "Image/png";
} else if (c1 = = && C2 = =) {//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 = = 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;
}
}

Get the true width and height of img

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.