当你需要处理图片时,如进行压缩图片时就需要首先得到原图片的宽和高,然后再按比例进行图片压缩,那如何得到图片的宽和高呢?上代码:
/**
* 获取图片宽度和高度
* @param
* @return 返回图片的宽度
*/
public static int[] getImgWidthHeight(File file) {
InputStream is = null;
BufferedImage src = null;
int result[] = { 0, 0 };
try {
// 获得文件输入流
is = new FileInputStream(file);
// 从流里将图片写入缓冲图片区
src = ImageIO.read(is);
result[0] =src.getWidth(null); // 得到源图片宽
result[1] =src.getHeight(null);// 得到源图片高
is.close(); //关闭输入流
src = null;
} catch (Exception ef) {
ef.printStackTrace();
}
System.gc();
return result;
}
如此变获得原图的宽和高了,后面就可以对此图片进行操作了。如进行压缩图片。