BitmapFactory.Option实现缩略图

本文介绍如何通过调整BitmapFactory.Options中的inSampleSize和inJustDecodeBounds参数来减少图片占用的内存,避免因图片过大导致的内存溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在对图片进行操作的过程中,可能出现图片过大造成内存溢出的情况,出现这样的错误我们就可以缩小图片的大小,这样就不会报错了,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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值