`
夏文权
  • 浏览: 237300 次
  • 性别: Icon_minigender_1
  • 来自: 贵州
社区版块
存档分类
最新评论

android 图片缩放

 
阅读更多
写道
最近在弄图片,遇到了一些内存溢出的问题,在网上看到的文章还不错,摘下来。

需要显示图片的缩略图或者在拍照上传的时候,而一般情况下,我们要将图片按照固定大小取缩略图,一般取缩略图的方法是使用BitmapFactory的decodeFile方法,
然后通过传递进去 BitmapFactory.Option类型的参数进行取缩略图,在Option中,属性值inSampleSize表示缩略图大小为原始图片大小的几分之一,即如果这个值为2,则取出的缩略图的宽和高都是原始图片的1/2,图片大小就为原始大小的1/4。

然而,如果我们想取固定大小的缩略图就比较困难了,比如,我们想将不同大小的图片去出来的缩略图高度都为200dip,而且要保证图片不失真,那怎么办?我们总不能将原始图片加载到内存中再进行缩放处理吧,要知道在移动开发中,内存是相当宝贵的,而且一张100K的图片,加载完所占用的内存何止 100K?

经过研究发现,Options中有个属性inJustDecodeBounds,研究了一下,终于明白是什么意思了,SDK中的E文是这么说的
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

意思就是说如果该值设为true那么将不返回实际的bitmap不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息,那么相应的方法也就出来了,
通过设置inJustDecodeBounds为true,获取到outHeight(图片原始高度)和 outWidth(图片的原始宽度),然后计算一个inSampleSize(缩放值),然后就可以取图片了,这里要注意的是,inSampleSize 可能小于0,必须做判断。

 

 

实例代码:

/**
	 * 压缩图片
	 * @param path 文件路径
	 * @param w 屏幕的宽
	 * @param h 屏幕的高
	 * @return
	 */
	public static  Bitmap decodeBitmap(String path,int w, int h ) {
       
		BitmapFactory.Options op = new BitmapFactory.Options();
		//值设为true,将不返回实际的bitmap不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息
        op.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(path, op); // 获取尺寸信息
        System.out.println("op.outWidth ====== " + op.outWidth);
        System.out.println("op.outHeight ====== " + op.outHeight);
        
        System.out.println("w ====== " + w);
        System.out.println("h ====== " + h);
        // 获取比例大小
        int wRatio = (int) Math.ceil(op.outWidth / w);
        int hRatio = (int) Math.ceil(op.outHeight / h);
        
        System.out.println("w ====== " + wRatio);
        System.out.println("h ====== " + hRatio);
        
        // 如果超出指定大小,则缩小相应的比例
        if (wRatio > 1 && hRatio > 1) {
            if (wRatio > hRatio) {
                op.inSampleSize = wRatio;
            } else {
                op.inSampleSize = hRatio;
            }
        }
        op.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeFile(path, op);
        return bmp;
    }
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics