推荐第一种,效率高,第二,第三种方法无法加载大图片,代码如下:
/**
* 图片缩放1
*/
public static Bitmap scaleBitmap(String pathName, int newWidth,
int newHeight) {
// options为true时,只返回bitmap的信息,不加载bitmap到内存,效率高
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// inSampleSize是缩放比例,例,为2,那就是原图宽高都缩小为1/2;
// inSmpleSize有可能为负数,所以与1比较
options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
(double) options.outWidth / newWidth,
(double) options.outHeight / newHeight)));
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
return bitmap;
}
/**
* 图片缩放2
*/
public static Bitmap scaleBitmap2(String pathName, int newWidth,
int newHeight) {
// 加载原图
Bitmap bm = BitmapFactory.decodeFile(pathName);
// 得到缩略图
Bitmap bitmap = ThumbnailUtils
.extractThumbnail(bm, newWidth, newHeight);
return bitmap;
}
/**
* 图片缩放3
*/
public static Bitmap scaleBitmap3(String pathName, int newWidth,
int newHeight) {
// 加载原图
Bitmap bm = BitmapFactory.decodeFile(pathName);
Matrix matrix = new Matrix();
// 得到x,y方向的缩放比例
float sx = newWidth * 1.0f / bm.getWidth();
float sy = newHeight * 1.0f / bm.getHeight();
// 得到缩略图的矩阵
matrix.postScale(sx, sy);
// 得到缩略图
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
return bitmap;
}