本文共 3268 字,大约阅读时间需要 10 分钟。
在Android开发过程中,频繁加载高分辨率图片可能导致内存不足(OOM),这时候就需要通过图片压缩和优化来解决问题。本文将详细介绍Android中获取图片资源的优化方法,帮助开发者避免内存溢出问题。
在Android中获取图片资源有两种主要方式:从应用程序的资源文件(通过Resources类)或者外部存储(如sdcard)读取图片文件。针对这两种方式,我们将分别介绍图片优化加载的实现方法。
为了高效加载图片资源,Android提供了BitmapFactory类。如果直接用BitmapFactory.decodeResource方法加载图片,可能会因为图片分辨率过高导致内存不足。因此,我们需要对图片进行比例削减,同时保留足够的细节来显示图片。
整体思路如下:
具体实现步骤如下:
获取图片尺寸:使用BitmapFactory.Options类设置inJustDecodeBounds属性,首先解析图片,并获取原始尺寸。注意,这一步不需要将图片全部加载入内存,只是获取原始尺寸即可。
计算样本比例:计算原始图片宽高与目标显示宽高的比率,取最小的比率作为画面的样本比例。这样得到的样本比例可以确保图片在显示时不缺失重要细节。
削减图片大小:使用计算出的样本比例,将图片的尺寸缩放至适当大小。需要注意的是,在进行比例削减时,保持图片质量的同时也要兼顾加载速度。
外部存储(如sdcard)存储的图片文件同样需要进行优化处理。加载图片文件时也需要考虑文件路径、图片大小和分辨率等因素。
完整的处理流程如下:
幅度削减的关键在于合理选择inSampleSize。以下是详细的计算方法:
在 calculateInSampleSize 函数中:
代码示例:
public int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize;}
基于上述方法,完整的优化加载图片的实现代码如下:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options);}public static Bitmap decodeSampledBitmapFromSdcard(String filepath, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filepath, options);}public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize;}
通过以上方法,可以有效地对图片进行降采样,避免重复计算资源,并显著减少内存占用。在实际开发中,可以根据具体需求调整样本比例,以平衡图片质量和加载速度。
通过合理使用这些优化方法,可以有效避免OOM问题,并提升应用的启动速度和性能表现。
转载地址:http://mqgez.baihongyu.com/