public class Utils {
// shell 命令查看程序内存使用情况
// : adb shell dumpsys meminfo packageName
//dalvik.system.VMRuntime
/***
* 增强程序堆内存的处理效率.
* private final static float TARGET_HEAP_UTILIZATION = 0.75f;
* 在程序onCreate时就可以调用
* VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。
*/
/***
* 强制定义自己软件的对内存大小
* private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
* VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。
*/
/**
* 计算原始图片与缩放图片的比例
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
/***
* 设置合适的sampleSize后获取图片
* @param res
* @param resId
* @param reqWidth
* @param reqHeight
* @return
*/
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);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/***
* 以最省内存的方式读取本地资源的图片
* @param context
* @param resId
* @return
*/
public static Bitmap readBitmap(Context context,int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
//获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}
/**
* Reads this input stream and returns contents as a byte[] 将流中的内容解释为byte[]
* 数组 from:aspectjweaver.jar
*/
public static byte[] readAsByteArray(InputStream inStream)
throws IOException {
int size = 1024;
byte[] buff = new byte[size];
int readSoFar = 0;
while (true) {
int nRead = inStream.read(buff, readSoFar, size - readSoFar);
if (nRead == -1) {
break;
}
readSoFar += nRead;
if (readSoFar == size) {
int newSize = size * 2;
byte[] newBuff = new byte[newSize];
System.arraycopy(buff, 0, newBuff, 0, size);
buff = newBuff;
size = newSize;
}
}
byte[] newBuff = new byte[readSoFar];
System.arraycopy(buff, 0, newBuff, 0, readSoFar);
return newBuff;
}
}