java--获取图片效率差异

	public static void compare() throws Exception{
		long start1 = System.currentTimeMillis();
		for (int i = 0; i < 5000; i++) {

			Iterator readers = ImageIO.getImageReadersByFormatName("png");
			ImageReader reader = (ImageReader) readers.next();
			File file = new File("d://1.png");
			ImageInputStream input = ImageIO.createImageInputStream(file);
			reader.setInput(input, true);
			int width = reader.getWidth(0);
			int height = reader.getHeight(0);
			//System.out.println(width + "/" + height);
		}

		long end1 = System.currentTimeMillis();

		System.out.println(end1 - start1);
		long start2 = System.currentTimeMillis();
		for (int i = 0; i < 5000; i++) {
			File file = new File("d://1.png");
			BufferedImage bi = ImageIO.read(file);
			int width = bi.getWidth();
			int height = bi.getHeight();
			//System.out.println(width + "/" + height);
		}

		long end2 = System.currentTimeMillis();
		System.out.println(end2 - start2);
	}

运行结果

390
3192

可见第一中获取图片信息效率明显高于第二种。


看了下源码第一种方法只适用于简单的操作。

而第二种适用的范围比较广,在ImageIO源码中也适用了ImageReader。


参考:http://houxiyang.com/archives/31/

你可能感兴趣的:(图片)