二次采样工具类
public class BitmapUtils {
/**
* @param filePath 要加载的图片路径
* @param destWidth 显示图片的控件宽度
* @param destHeight 显示图片的控件的高度
* @return
*/
public static Bitmap getBitmap(String filePath, int destWidth, int destHeight) {
//第一次采样
BitmapFactory.Options options = new BitmapFactory.Options();
//该属性设置为true只会加载图片的边框进来,并不会加载图片具体的像素点
options.inJustDecodeBounds = true;
//第一次加载图片,这时只会加载图片的边框进来,并不会加载图片中的像素点
BitmapFactory.decodeFile(filePath, options);
//获得原图的宽和高
int outWidth = options.outWidth;
int outHeight = options.outHeight;
//定义缩放比例
int sampleSize = 1;
while (outHeight / sampleSize > destHeight || outWidth / sampleSize > destWidth) {
//如果宽高的任意一方的缩放比例没有达到要求,都继续增大缩放比例
//sampleSize应该为2的n次幂,如果给sampleSize设置的数字不是2的n次幂,那么系统会就近取值
sampleSize *= 2;
}
/********************************************************************************************/
//至此,第一次采样已经结束,我们已经成功的计算出了sampleSize的大小
/********************************************************************************************/
//二次采样开始
//二次采样时我需要将图片加载出来显示,不能只加载图片的框架,因此inJustDecodeBounds属性要设置为false
options.inJustDecodeBounds = false;
//设置缩放比例
options.inSampleSize = sampleSize;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//加载图片并返回
return BitmapFactory.decodeFile(filePath, options);
}
}
使用方法
把我们原始图片的路径传给 这个工具类 会返回一个Bitmap
当然 之后我们也可以再把这个Bitmap 图片储存到本地 获取到一个新的 采样后的图片路径和图片file
//把头像缓存到sd卡的方法
private void setPicToView(Bitmap mBitmap) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
return;
}
FileOutputStream b = null;
File file = new File(path);
file.mkdirs();// 创建文件夹
fileName = path + "/image.png";//图片名字
File fileImage = new File(fileName);
if (!fileImage.exists()) {
try {
fileImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
b = new FileOutputStream(fileImage);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
//关闭流
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
再附个 获取屏幕宽度高度 的方法 和获取 系统储存路径的方法
获取屏幕宽度高度的四种方法
方法一:
WindowManager wm = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
方法二:
WindowManager wm1 = this.getWindowManager();
int width1 = wm1.getDefaultDisplay().getWidth();
int height1 = wm1.getDefaultDisplay().getHeight();
方法一与方法二获取屏幕宽度的方法类似,只是获取WindowManager 对象时的途径不同。
方法三:
WindowManager manager = this.getWindowManager();
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
int width2 = outMetrics.widthPixels;
int height2 = outMetrics.heightPixels;
方法四:
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density1 = dm.density;
int width3 = dm.widthPixels;
系统储存路径
//sd路径
private static String path;
path = Environment.getExternalStorageDirectory() + "/image";