高效的使用Bitmap-创新互联

在Android经常使用到Bitmap用于显示图片,如果图片过大,容易出现"OutOfMemory"异常,所以要对图片进行压缩显示。

创新互联公司-专业网站定制、快速模板网站建设、高性价比丽江网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式丽江网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖丽江地区。费用合理售后完善,十年实体公司更值得信赖。

通常使用BitmapFactory类的几个方法(decodeByteArray(), decodeFile(), decodeResource()等)来建立一个bitmap,在生成bitmap前,可以通过BitmapFactory.Options来设置属性,来保证不会出现OutOfMemory异常。首先可以通过需要显示图片的长宽来获取缩小的倍数:

private int calculateInSampleSize(BitmapFactory.Options options,
                int reqWidth, int reqHeight) {
        // Raw height and width of p_w_picpath
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                 inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                 inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
	}

PS:官方文档说到,图片压缩时,使用2的倍数压缩效率会高,就是2,4,8…这种,我这里使用的是更接近需要的压缩倍数,官方文档看这里。

使用两种方式来压缩图片,一种是根据需要的图片长宽,一种是根据需要的图片大小(就是多少K)。

先看第一种:

public Bitmap GetThumbImageByWH(boolean isRound,String imgPath, int p_w_picpathwidth, int p_w_picpathheight) {
		try {
			File picture = new File(imgPath);
			BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
			// set height and width of p_w_picpath
			bitmapFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
					bitmapFactoryOptions);
			int inSampleSize = calculateInSampleSize(bitmapFactoryOptions,p_w_picpathwidth,p_w_picpathheight);
						
			bitmapFactoryOptions.inSampleSize = inSampleSize;
			bitmapFactoryOptions.inJustDecodeBounds = false;
			bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
					bitmapFactoryOptions);

			return bmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

PS:如果使用一个BitmapFactory.Options对象,要先把该对象的inJustDecodeBounds属性设置为true,inSampleSize设置完成后再设置为false。后面的是用来翻转图片的。

第二种方式:

public Bitmap getThumbImageBySize(String imgpath, int size, boolean adjustOrientation) {
		File file=new File(imgpath);
		FileInputStream fis = null;
		int filesize=0;
		try{
			fis = new FileInputStream(file);
			filesize = fis.available();
			Log.v("file length", ""+filesize);
			fis.close();			
		}catch(Exception ex){
			Log.v("Read file error", ""+ex.getMessage());
		}
		if(filesize/1024

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文名称:高效的使用Bitmap-创新互联
网站网址:http://myzitong.com/article/coioso.html