首页 > 代码库 > 解决了OOM的问题
解决了OOM的问题
public class ImageUtils
{
/**
* 从SDCard读取图片时压缩
*
* @param srcPath
* @return
*/
public static Bitmap compressImageFromFile(String srcPath,
float ww, float hh )
{
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;// 只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// float hh = 800f;//
// float ww = 480f;//
int be = 1;
// 缩放到可以在480x800的屏幕上完整显示图片
if (w >= h && w >= ww)
{
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh)
{
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 设置采样率
newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
newOpts.inPurgeable = true;// 同时设置才会有效
newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return bitmap;
}
/**
* 将图片在内存中压缩
*
* @param image
* @return
*/
public static Bitmap compressBmpFromBmp(Bitmap image)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 压缩到刚好小于100kb为止
while (baos.toByteArray().length / 1024 > 100)
{
baos.reset();
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
}
本文出自 “android技术” 博客,请务必保留此出处http://340431827.blog.51cto.com/9096201/1533220