Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Android 按指定大小读取图片的实例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

在android开发中,我们经常遇到Android读取图片大小超过屏幕显示的图(一般只要显示一定规格的预览图即可),在图片特别多或者图片显示很频繁的时候要特别注意这个问题,下面介绍个按指定大小读取图像的方法

实现原理:首先获取图片文件的图像高和宽,如果小于指定比例,则直接读取;如果超过比例则按指定比例压缩读取。

捕获OutOfMemoryError时注意点:后面返回的是null,不要马上从别的地方再读图片包括R文件中的,不然依然会抛出这个异常,一般在初始化的时候缓存图片,然后显示缓存中的图片

/** 获取图像的宽高**/

public static int[] getImageWH(String path) {
	int[] wh = {-1,-1};
 if (path == null) {
 	return wh;
 }
 File file = new File(path);
 if (file.exists() && !file.isDirectory()) {
  try {
   BitmapFactory.options options = new BitmapFactory.options();
   options.inJustDecodeBounds = true;
   InputStream is = new FileInputStream(path);
   BitmapFactory.decodeStream(is,null,options);
   wh[0] = options.outWidth;
   wh[1] = options.outHeight;
  }
  catch (Exception E) {
   Log.w(tag,"getImageWH Exception.",E);
  }
 }
 return wh;
}
 
public static Bitmap createBitmapByScale(String path,int scalE) {
	Bitmap bm = null;
 try {
 	//获取宽高
  int[] wh = getImageWH(path);
  if (wh[0] == -1 || wh[1] == -1) {
  	return null;
  }

  //读取图片
  BitmapFactory.options options = new BitmapFactory.options();
  options.inSampleSize = Math.max(wh[0]/scale,wh[1]/scalE);
  InputStream is = new FileInputStream(path);
  	bm = BitmapFactory.decodeStream(is,options);
 }
 catch (Exception E) {
 	Log.w(tag,"createBitmapByScale Exception.",E);
 }
 catch (OutOfMemoryError E) {
  Log.w(tag,"createBitmapByScale OutOfMemoryError.",E);
  //TODO: out of memory deal..
 }
 return bm;
}

以上就是解决Android 读取图片大小显示的问题,有需要的朋友可以参下。

大佬总结

以上是大佬教程为你收集整理的Android 按指定大小读取图片的实例全部内容,希望文章能够帮你解决Android 按指定大小读取图片的实例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。