我们在对图片进行操作的过程中,可能出现图片过大造成内存溢出的情况,出现这样的错误我们就可以缩小图片的大小,这样就不会报错了,BitmapFactory.Option中就实现了这样的操作,其中主要的两个参数是:inSampleSize和inJustDecodeBounds
其中
inSampleSize在API帮助文档中是这样表述的:If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.意思就是当它的值大于1的时候,会返回一个更小的图片来节省内存,例如inSampleSize=2,就会返回一个长宽都减半的图片,即图片大小为原图的1/4.
inJustDecodeBounds在API帮助文档中是这样表述的: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,但会的到图片的尺寸信息,并允许指定内存。
得到缩略图的步骤:
1.BitmapFactory.Option option
2.inJustDecodeBounds=true;
option.outheight;
option.outwidth;
scale=缩放值;
3.得到bitmap;
4.inSampleSize=scale;
inJustDecodeBounds=false;
public class MainActivity extends AppCompatActivity {
public ImageView image=null;
public String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image=findViewById(R.id.text_image);
image.setImageBitmap(smallBitmap("/sdcard/.jpg") ) ;
}
//Phone Storage/sina/weibo/img-7738dc22c063345ac560124c7286fb7.jpg /sdcard/MTXX/3.jpg
public Bitmap smallBitmap(String filepath){
BitmapFactory.Options options=new BitmapFactory.Options() ;
options .inJustDecodeBounds =true;
int realHeight=options .outHeight;
int realWidth=options .outWidth ;
Bitmap bitmap=BitmapFactory.decodeFile(filepath,options );
if(bitmap ==null){
System.out.println("图片不存在") ;
}
int scale=4;
if(scale<=1){
scale=1;
}
options .inSampleSize =scale ;
options .inJustDecodeBounds =false ;
bitmap=BitmapFactory.decodeFile(filepath ,options );
return bitmap;
}
}