Bitmap类及BitmapFactory类中的常用方法

本文介绍Bitmap在Android中的加载方式及优化技巧,包括不同资源路径下的加载方法、内存占用计算及如何通过BitmapFactory.Options减少内存消耗。

http://blog.csdn.net/coderyue/article/details/50103639#t9      Bitmap总结

https://www.cnblogs.com/wangjiaghe/p/7358445.html

http://blog.csdn.net/zxw136511485/article/details/51957962

http://blog.csdn.net/u012637501/article/details/40832893

1.assets目录下资源加载  

如果图片保存到assest目录下,知道图片的名称,则可以通过inputstream获得图片Drawable或者 Bitmap
AssetManager asm=getAssets();
        InputStream is;
        try {
            is = asm.open("smiley_smile.png");
            //获得Drawable
            Drawable da = Drawable.createFromStream(is, null);
            //获得Bitmap
            Bitmap bitmap=BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

2、图片保存在sdcard,通过图片的路径加载,可以使用BitmapFactory的方法加载,举个例子

// 图片路径
        String imgFilePath = Environment.getExternalStorageDirectory()
                .toString() + "/smiley_smile.png";
        try {
            // 获得文件输入流
            FileInputStream fis = new FileInputStream(new File(imgFilePath));
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Bitmap.createBitmap(bitmap, x, y, pieceWidth, pieceWidth)                          以X,Y坐标(左上角)为起点,而宽与高则是width与height(右下角 )开始截图    

BitmapFactory类提供了几个解析方法,每种解码方法都可以让你通过BitmapFactory.Options设置标签。设置inJustDecodeBounds 为true,解码的时候会避免内存的分配,返回的bitmap对象为空,但是却可以得到 outWidth, outHeight 和outMimeType。


BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

为了避免 java.lang.OutOfMemory 异常,在解析前先核对Bitmap的尺寸,除非你有绝对的把握你的图片不会造成内存溢出。

是否加载一个按比例缩小的版本到内存中,下面几点可以考虑:

1.估算加载完整图片使用的内存大小。
2.加载了完整图片,给应用其他的内存需求大小
3.目标Imageview尺寸或者加载图片的UI组建大小
4.当前设备屏幕尺寸或者大小
5.告诉解码器对Image进行采样,加载一个较小版本图片到内存中,设置BitmapFactory.Options 对象inSampleSize为true。比如一个2048*1536密度的图片,inSampleSize为4生成的样品图就是512*384。加载这个样品需要内存0.75MB,而不是原来的12MB。下面提供了方法计算样本大小。

把任意尺寸图显示成100*100的缩略图:
Bitmap bitmap = decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
第一步设置inJustDecodeBounds = true,然后通过新的inSampleSize解码,最后设置inJustDecodeBounds = false。
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // 第一步inJustDecodeBounds=true 检查尺寸大小
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // 计算样本尺寸
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // 进行采样
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // 原始图片大小
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

       //计算最大的压缩比例值都是2的幂次方,而且宽和高大于被要求  
       //的宽和高。           
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

WeakReference<ImageView> imageViewReference = new WeakReference<ImageView>(imageView);// 使用弱引用,确保可以被回收

imageViewReference.get();    //弱引用是为了确保能被回收,无法保证当任务完成的时候ImageView还在,所以需要核对。

1.Bitmap

  • public void recycle()——回收位图占用的内存空间,把位图标记为Dead
  • public final boolean isRecycled() ——判断位图内存是否已释放
  • public final int getWidth()——获取位图的宽度
  • public final int getHeight()——获取位图的高度
  • public final boolean isMutable()——图片是否可修改
  • public int getScaledWidth(Canvas canvas)——获取指定密度转换后的图像的宽度
  • public int getScaledHeight(Canvas canvas)——获取指定密度转换后的图像的高度
  • public boolean compress(CompressFormat format, int quality, - - --OutputStream stream)——按指定的图片格式以及画质,将图片转换为输出流。
  • format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置

2.BitmapFactory

2.1 BitmapFactory创建Bitmap的几种方法说明

1.publicstatic Bitmap decodeByteArray (byte[] data,int offset, int length, BitmapFactory.Options opts)
参数
data    压缩图像数据的字节数组
offset  图像数据偏移量,用于解码器开始从哪儿解析.
length  字节数,以偏移量开始,去解析
opts    可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
返回值
    返回解码后的位图,或者如果图像数据不能被解码返回为空,或者 如果选项不是空,如果选项要求仅仅返回大小(opts.outWidth and opts.outHeight)。
从指定的字节数组中解码一个不可变的位图。

 

2. public static Bitmap decodeByteArray (byte[] data, int offset, int length)
参数
data 压缩图像数据的字节数组
offset 图像数据偏移量,用于解码器开始从哪儿解析.
length 字节数,以偏移量开始,去解析
返回值
返回解码后的位图,或者如果图像数据不能被解码返回为空
从指定的字节数组中解码一个不可变的位图。

 

3.public staticBitmap decodeFile (String pathName)
参数
pathName    解码文件的全路径名
返回值
    返回结果是解码的位图,或者如果不能解码则返回空。
从文件中解码生成一个位图。如果支付的文件名为空,或者不能解码出一个位图,方法将返回空。

 

4.public staticBitmap decodeFile (String pathName, BitmapFactory.Options opts)
参数
pathName    解码文件的全路径名
opts            可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
Returns
    返回解码后的位图,或者如果图像数据不能被解码返回为空,或者 如果选项不是空,如果选项要求仅仅返回大小(opts.outWidth and opts.outHeight)。
从文件中解码生成一个位图。如果支付的文件名为空,或者不能解码出一个位图,方法将返回空。

 

5.public staticBitmap decodeFileDescriptor (FileDescriptor fd)
参数
fd  包含解码位图数据的文件路径
返回值
   返回解码的位图或者空。

 

6.public staticBitmap decodeFileDescriptor (FileDescriptor fd, Rect outPadding, BitmapFactory.Options opts)
参数
fd          包含解码位图数据的<span style="font-family: Arial, Helvetica, sans-serif;">文件路径</span>
outPadding  如果不为空,返回矩形的内边距如果位图存在,否则设置内边距为(-1,-1,-1,-1).如果没有位图返回空,内边距不改变
opts            可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
返回值
    返回解码的位图或者空。

 

7.public staticBitmap decodeResource (Resources res, intid, BitmapFactory.Options opts)
参数
res     包含图像数据的资源对象
id  图像数据的资源的id
opts    可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
返回值

 

8.public staticBitmap decodeResourceStream (Resources res, TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts)
从输入流中解码一个新位图。输入了获得资源,我们可以缩放位图。

 

9.public staticBitmap decodeResource (Resources res, intid)
参数
res         包含图像数据的资源对象
id      图像数据的资源的id
返回值
    返回解码后的位图,或者如果图像数据不能被解码返回为空
从输入流中解码位图。与decodeResource(Resources,int, android.graphics.BitmapFactory.Options)当Options是空时同义,

 

10.public staticBitmap decodeResource (Resources res, intid, BitmapFactory.Options opts)
参数
res     包含图像数据的资源对象
id  图像数据的资源的id
opts    可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
返回值
   返回解码后的位图,或者如果图像数据不能被解码返回为空,或者 如果选项不是空,如果选项要求仅仅返回大小(opts.outWidth and opts.outHeight)。
从资源中解码一个位图。与decodeResourceStream(Resources, TypedValue, InputStream, Rect, BitmapFactory.Options)同义.

 

11.public staticBitmap decodeStream (InputStream is, Rect outPadding, BitmapFactory.Options opts)
参数
is          持有原始数据用于解码位图的输入流
outPadding  如果不为空,返回矩形的内边距如果位图存在,否则设置内边距为(-1,-1,-1,-1).如果没有位图返回空,内边距不改变
opts            可以为空,控制采样率和实付图像完全被解码的选项,或者仅仅返回大小
Returns
    返回解码后的位图,或者如果图像数据不能被解码返回为空,或者 如果选项不是空,如果选项要求仅仅返回大小(opts.outWidth and opts.outHeight)。
从输入流中解码一个位图。如果输入了为空,或者不能解码位图,方法返回空。流的位置觉得解码数据从哪儿读取。

 

12.public staticBitmap decodeStream (InputStream is)
Decode an input stream into a bitmap. If the input stream isnull, or cannot be used to decode a bitmap, the function returnsnull. The stream's position will be where ever it was after the encoded data was read.
参数
is  持有原始数据用于解码位图的输入流
返回值
    返回解码后的位图,或者如果图像数据不能被解码返回为空

2.2 BitmapFactory.Options说明以及使用

位图在内存中的占用空间计算:
ALPHA_8:每个像素占用1byte内存
ARGB_4444:每个像素占用2byte内存
ARGB_8888:每个像素占用4byte内存
RGB_565:每个像素占用2byte内存
举个例子,如果一个图片的分辨率是1024*768,采用ARGB_8888,那么占用的空间就是1024*768*4=3MB

 

通过BitmapFactory.Options降低bitmap加载到内存中的内存及改变色彩设置防止OOM

BitmapFactory.Options的常用参数

inJustDecodeBounds:

如果将这个值置为true,那么在解码的时候将不会返回bitmap,只会返回这个bitmap的尺寸。这个属性的目的是,如果你只想知道一个bitmap的尺寸,但又不想将其加载到内存时。这是一个非常有用的属性。

inSampleSize:

缩放比例。当它小于1的时候,将会被当做1处理,这个参数需要是2的幂函数。例如,width=100,height=100,inSampleSize=2,那么就会将bitmap处理为,width=50,height=50,宽高各降为1 / 2,像素数降为1 / 4。

inPreferredConfig:

这个值是设置色彩模式,默认值是ARGB_8888,在这个模式下,一个像素点占用4bytes空间,一般对透明度不做要求的话,一般采用RGB_565模式,这个模式下一个像素点占用2bytes。

outWidth和outHeight:

表示这个Bitmap的宽和高,一般和inJustDecodeBounds一起使用来获得Bitmap的宽高,但是不加载到内存。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值