Bitmap基础

来源:互联网 发布:mac安装flash插件 编辑:程序博客网 时间:2024/05/19 01:33

读取Bitmap的方法

1.BitmapFactory.decodeStream();方法 网络图片


1.2.BitmapFactory.decodeResource();方法res/drawable


1.3.BitmapFactory.decodeFile();方法 某个文件下



保存bitmap图片

bitmap.compress(CompressFormat.PNG, 100, fos);


compress方法里第二个参数标示压缩率。

例:30 是压缩率,表示压缩70%; 如果不压缩是100,表示压缩率为0  。


//以保存imageview里的图片为例

imageview.setDrawingCacheEnabled(true);


bitmap=Bitmap.createBitmap(imageview.getDrawingCache());


imageview.setDrawingCacheEnabled(false);


StringPath="/bridgebetweencolleges/"+UUID.randomUUID().toString()+".png";


if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){


File sdCardDir=Environment.getExternalStorageDirectory();


FileOutputStream fos=null;


try {


File file=new File(sdCardDir, strPath);


if(!file.getParentFile().exists()){


file.getParentFile().mkdirs();


}


fos=new FileOutputStream(file);


//当指定压缩格式为PNG时保存下来的图片显示正常

bitmap.compress(CompressFormat.PNG, 100, fos);


//当指定压缩格式为JPEG时保存下来的图片背景为黑色


fos.flush();


}catch (Exception e){


e.printStackTrace();


finally{


try{


fos.close();


}catch (IOException e){


e.printStackTrace();


}


}


toast.showToast("成功保存图片到SD卡!");


}else{


toast.showToast("SD卡有误不可保存图片!");


}



销毁bitmap

if(bitmap!=null){

if(!bitmap.isRecycled()){  

bitmap.recycle();  

}

}




BitmapFactory.Options图片资源太大的适合,会出现内存溢出。解决方法


BitmapFactory.Options使用


BitmapFactory.Options options=new BitmapFactory.Options();

options.inJustDecodeBounds=true;

Bitmap bmp=BitmapFactory.decodeFile(path, options);这里返回的bmp是null */


BitmapFactory.Options属性


inJustDecodeBounds:

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


inSampleSize:

这个值是一个int,当它小于1的时候,将会被当做1处理,如果大于1,那么就会按照比例(1 / inSampleSize)缩小bitmap的宽和高、降低分辨率,大于1时这个值将会被处置为2的倍数。例如,width=100,height=100,inSampleSize=2,那么就会将bitmap处理为,width=50,height=50,宽高降为1 / 2,像素数降为1 / 4。

 

inPreferredConfig:

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


inPremultiplied:

这个值和透明度通道有关,默认值是true,如果设置为true,则返回的bitmap的颜色通道上会预先附加上透明度通道。


inDither:

这个值和抖动解码有关,默认值为false,表示不采用抖动解码。


inDensity:

表示这个bitmap的像素密度(对应的是DisplayMetrics中的densityDpi,不是density)。


inTargetDensity:

表示要被画出来时的目标像素密度(对应的是DisplayMetrics中的densityDpi,不是density)。


inScreenDensity:

表示实际设备的像素密度(对应的是DisplayMetrics中的densityDpi,不是density)。


inScaled:

设置这个Bitmap是否可以被缩放,默认值是true,表示可以被缩放。


inPurgeable和inInputShareable:

这两个值一般是一起使用,设置为true时,前者表示空间不够是否可以被释放,后者表示是否可以共享引用。这两个值在Android5.0后被弃用。


inPreferQualityOverSpeed:

这个值表示是否在解码时图片有更高的品质,仅用于JPEG格式。如果设置为true,则图片会有更高的品质,但是会解码速度会很慢。


outWidth和outHeight:

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



0 0
原创粉丝点击