内存溢出应对:把图片固定大小赋值给bitmap
2017-12-13 12:23
113 查看
主题://将绝对路径转换为Bitmap,动态计算inSampleSize限制图片大小此处大小为128*128 RGB_565(默认为8888)下为 2.7K public static Bitmap getFixedSizeImg(String filePath){ Bitmap bitmap = null; BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inPurgeable = true; opts.inInputShareable = true; BitmapFactory.decodeFile(filePath, opts); opts.inSampleSize = computeSampleSize(opts, -1, 128*128); opts.inJustDecodeBounds = false; try { bitmap = BitmapFactory.decodeFile(filePath, opts); }catch (Exception e) { // TODO: handle exception } return bitmap; } //计算inSampleSize public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } //计算inSampleSize private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } } 主题结束 重写Activity此方法可查看app内存状态@Override public void onTrimMemory(int level) { super.onTrimMemory(level); switch (level) { case TRIM_MEMORY_RUNNING_MODERATE: LongLog.loge("你的app正在运行并且不会被列为可杀死的"); break; case TRIM_MEMORY_RUNNING_LOW: LongLog.loge("你的app正在运行且没有被列为可杀死的"); break; case TRIM_MEMORY_RUNNING_CRITICAL: LongLog.loge("你的app仍在运行,但是系统已经把LRU Cache中的大多数进程都已经杀死"); break; case TRIM_MEMORY_BACKGROUND: LongLog.loge("系统正运行于低内存"); break; case TRIM_MEMORY_MODERATE: LongLog.loge(" 系统正运行于低内存状态并且你的进程已经已经接近LRU名单的中部位置"); break; case TRIM_MEMORY_COMPLETE: LongLog.loge("系统正运行与低内存的状态并且你的进程正处于LRU名单中最容易被杀掉的位置"); break; } }
相关文章推荐
- css样式--将大小不固定的图片或文字段 垂直居中
- 如何将网页所用图片裁剪成固定大小、合适文件大小(photoshop工具)
- 大小不固定的图片,多行文字水平垂直居中
- Bitmap——在不改变大小的情况下,如何以最省内存的方式读取本地资源的图片
- 利用canvas和bitmap如何对图片缩放到适应屏幕大小?
- 更改图片大小,显示固定尺寸
- cocos2d imageview 设置固定大小 不自适应图片大小
- 大小不固定的图片、多行文字的水平垂直居中
- PlusSlider 2个焦点图,一个可以固定图片宽和高一个显示实际大小
- CMS图片对应文字以及设置固定的大小
- Android编程之Bitmap图片压缩大小
- Android图片大小调整动态实现方法(bitmap)
- 大小不固定的图片和多行文字的垂直水平居中
- div css 伪类 不固定图片大小 居中, css div 实现三角形
- 通过bitmap改变图片的大小
- 图片的无极缩放与固定大小
- 任意大小的图片在固定容器居中显示
- 手机站图片设置固定比例大小
- 自定义在图片上贴固定大小的图片
- 使用BitmapFactory压缩图片大小