主题://将绝对路径转换为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; } }
内存溢出应对:把图片固定大小赋值给bitmap
最新推荐文章于 2024-02-10 07:00:00 发布