参考文件:
http://www.cnblogs.com/wanqieddy/archive/2011/11/25/2263381.html
图片处理主要考虑到OOM的问题,
下面就来说说处理的几个要素:
1.opetion配置
options.inJustDecodeBounds=true;
这个属性是判断是图否把图片读到内存,true是不读的。
int options.inSampleSize=10
缩放比为1/10
2强图片以流的形式打开,适合直接加载图片资源的形式,然后以流的形式解析
InputStream is =this.getResources().openRawResource(resId);
Bitmap bm = BitmapFactory.decodeStream(is, null, options);
3下面就是几个常见的方法咯:
1.图片压缩读取
private Bitmap getBitmap(int resId, int reqwidth, int resheight) {
final BitmapFactory.Options options = newBitmapFactory.Options();
options.inJustDecodeBounds = true;//不把图片读到内存,只计算大小
InputStream is =this.getResources().openRawResource(resId);
Bitmap q1 = BitmapFactory.decodeStream(is, null,options);
options.inSampleSize = calRatio(options, reqwidth,resheight);
Log.i("zxc", "---" +options.inSampleSize);
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeStream(is, null,options);
return bm;
}
2计算压缩比率
public int calRatio(BitmapFactory.Options options, intreqwidth, int reqheight) {
int ratio = 1;
int widthRatio = (int) (options.outWidth /reqwidth);
int heightRatio = (int) options.outHeight /reqheight;
ratio = widthRatio < heightRatio ? widthRatio :heightRatio;
return ratio;
}
3.设置图片的宽高
/**
* 处理图片
*
* @param bm 所要转换的bitmap
* @param newWidth//新的宽
* @param newHeight//新的高
* @return 指定宽高的bitmap
*/
public static Bitmap zoomImg(Bitmap bm, int newWidth, intnewHeight) {
// 获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片 www.2cto.com
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width,height, matrix, true);
return newbm;
}
4压缩图片到制定的大小KB
private Bitmap compressImage(Bitmap image,int size) {
ByteArrayOutputStream baos = newByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100,baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > size){ //循环判断如果压缩后图片是否大于100kb,大于继续压缩
Log.i("zxc","size(K)==" + baos.toByteArray().length / 1024);
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;//每次都减少10
}
Log.i("zxc", options + " ENDsize(K)==" + baos.toByteArray().length / 1024);
ByteArrayInputStream isBm = newByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm,null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}