图片二次采样有效防止因图片引起的OOM

来源:互联网 发布:淘宝怎么样投诉店家 编辑:程序博客网 时间:2024/04/28 07:30
OOM也就是我们经常遇到的:OutOfMenoryError 内存溢出异常

                        出现的原因那就是当加载的东西超出内存范围或内存不够用时会出现


                       

      解决方案:                      

                                   ExifInterface anInterface = new ExifInterface("图片路径")

                   //得到图片的宽和高
                                    int image_width = anInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0);
                                    int image_lenfth = anInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0);
                      //得到屏幕的宽和高
                                     WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                                     int screen_width = manager.getDefaultDisplay().getWidth();
                                     int screen_height = manager.getDefaultDisplay().getHeight();
                        //通过图片的宽和高以及屏幕的宽和高得到一个压缩比的值
                                    int width = image_width/screen_width;
                                    int height = image_lenfth/screen_height;
                                    int score = 0;
                                    if(width>=height&&width>1){
                                        score=width;
                                    }else if(height>=width&&height>1){
                                        score=height;
                                    }
                            //返回Bitmap对象                                     
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize=score;
                            Bitmap bitmap = BitmapFactory.decodeFile("图片路径",options);
                    

原创粉丝点击