大家都知道在Android平台上,显示图片时,容易出现bitmap outofmemory除了,对即使的回收bitmap,还有个方法,就是在使用前提前对图片进行处理
对图片进行缩放同时也减小了bitmap的大小
/**
* 缩放,压缩图片
* @param picPath
* @param width
* @param height
* @return
*/
public InputStream revitionPic(String picPath, int width, int height) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath, options);
options.inSampleSize = calcRatios(options, width, height);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);
//进一步较小图片的大小
return compressPic(bitmap);
}
计算缩放尺寸缩放比例
/**
* 计算缩放比例
* @param options
* @param width
* @param height
* @return
*/
protected int calcRatios(BitmapFactory.Options options, int width, int height) {
int origalWidth = options.outWidth;
int origalHeight = options.outHeight;
int inSampleSize = 1;
if(origalHeight > height || origalWidth > width) {
int heightRatios = Math.round(((float)origalHeight / (float)height));
int widthRatios = Math.round((float)origalWidth /(float)width);
inSampleSize = heightRatios > widthRatios ? widthRatios : heightRatios;
}
return inSampleSize;
}
压缩图片
/**
* 压缩图片
* @param pic
* @return
*/
public InputStream compressPic(Bitmap pic) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pic.compress(CompressFormat.JPEG, 100, baos);
int quality = 100;
while(quality > 0 && baos.toByteArray().length / 1024 > 100) {
//大于100k
baos.reset();
quality -= 5;
pic.compress(CompressFormat.JPEG, quality, baos);
}
return new ByteArrayInputStream(baos.toByteArray());
}