通过java获取图片的宽和高,很多时间可能都有这个需求了,下面是一个demo:
01 | import java.awt.image.BufferedImage; |
02 | import java.io.File; |
03 | import java.io.FileInputStream; |
04 | import java.io.InputStream; |
05 |
06 | /** |
07 | * 通过java获取图片的宽和高 |
08 | * @author sunlightcs |
09 | * 2011-6-1 |
11 | */ |
12 | public class ImageTools { |
13 | |
14 | /** |
15 | * 获取图片宽度 |
16 | * @param file 图片文件 |
17 | * @return 宽度 |
18 | */ |
19 | public static int getImgWidth(File file) { |
20 | InputStream is = null ; |
21 | BufferedImage src = null ; |
22 | int ret = - 1 ; |
23 | try { |
24 | is = new FileInputStream(file); |
25 | src = javax.imageio.ImageIO.read(is); |
26 | ret = src.getWidth( null ); // 得到源图宽 |
27 | is.close(); |
28 | } catch (Exception e) { |
29 | e.printStackTrace(); |
30 | } |
31 | return ret; |
32 | } |
33 | |
34 | |
35 | /** |
36 | * 获取图片高度 |
37 | * @param file 图片文件 |
38 | * @return 高度 |
39 | */ |
40 | public static int getImgHeight(File file) { |
41 | InputStream is = null ; |
42 | BufferedImage src = null ; |
43 | int ret = - 1 ; |
44 | try { |
45 | is = new FileInputStream(file); |
46 | src = javax.imageio.ImageIO.read(is); |
47 | ret = src.getHeight( null ); // 得到源图高 |
48 | is.close(); |
49 | } catch (Exception e) { |
50 | e.printStackTrace(); |
51 | } |
52 | return ret; |
53 | } |
54 | |