java快速获取大图片的分辨率(大图片格式JPG,tiff ,eg)(一)

2014-11-24 08:51:47 · 作者: · 浏览: 3
问题描述:怎样快速获取一个20MB图片的分辨率?
程序代码:
1 package test;
2
3 import java.awt.Dimension;
4 import java.awt.image.BufferedImage;
5 import java.io.File;
6 import java.io.IOException;
7 import java.util.Iterator;
8 import javax.imageio.ImageIO;
9 import javax.imageio.ImageReader;
10 import javax.imageio.stream.FileImageInputStream;
11 import javax.imageio.stream.ImageInputStream;
12
13 /**
14 * 读取大图片的分辨率
15 *
16 * @author 远方bruce
17 *
18 */
19 public class ReadResolution {
20 /**
21 * 通过BufferedImage获取
22 * @param file 文件
23 * @return 图片的分辨率
24 * @throws IOException
25 */
26 public static String getResolution1(File file) throws IOException {
27 BufferedImage image = ImageIO.read(file);
28 return image.getWidth() + "x" + image.getHeight();
29 }
30
31 /**
32 * 获取图片的分辨率
33 *
34 * @param path
35 * @return
36 */
37 public static Dimension getImageDim(String path) {
38 Dimension result = null;
39 String suffix = getFileSuffix(path);
40 //解码具有给定后缀的文件
41 Iterator iter = ImageIO.getImageReadersBySuffix(suffix);
42 System.out.println(ImageIO.getImageReadersBySuffix(suffix));
43 if (iter.hasNext()) {
44 ImageReader reader = iter.next();
45 try {
46 ImageInputStream stream = new FileImageInputStream(new File(
47 path));
48 reader.setInput(stream);
49 int width = reader.getWidth(reader.getMinIndex());
50 int height = reader.getHeight(reader.getMinIndex());
51 result = new Dimension(width, height);
52 } catch (IOException e) {
53 e.printStackTrace();
54 } finally {
55 reader.dispose();
56 }
57 }
58 System.out.println("getImageDim:" + result);
59 return result;
60 }
61
62 /**
63 * 获得图片的后缀名
64 * @param path
65 * @return
66 */
67 private static String getFileSuffix(final String path) {
68 String result = null;
69 if (path != null) {
70 result = "";
71 if (path.lastIndexOf('.') != -1) {
72 result = path.substring(path.lastIndexOf('.'));
73 if (result.startsWith(".")) {
74 result = result.substring(1);
75 }
76 }
77 }
78 System.out.println("getFileSuffix:" + result);
79 return result;
80 }
81
82 /**
83 * 截取Dimension对象获得分辨率
84 * @param path
85 *
86 * @return
87 */
88 public static String getResolution2(String path) {
89 String s = getImageDim(path).toString();
90 s = s.substring(s.indexOf("[") + 1, s.indexOf("]"));
91 String w = s.substring(s.indexOf("=") + 1, s.indexOf(","));
92 String h = s.substring(s.lastIndexOf("=") + 1);
93 String result = w + " x " + h;
94 System.out.println("getResolution:" + result);
95 return result;
96 }
97
98 /**
99 * 测试
100 *
101 * @param args
102 * @throws IOException
103 */
104 public static void main(String[] args) throws IOException {
105 S