如果一个内存比较大的图片加载在App上时会直接运行失败,所以要先通过解析生成一张缩略图
可以使用 BitmapFactory 类来解析 Bitmap 信息,解析过程可以先获取宽高,然后计算比例,然后解码像素信息
public static Bitmap decodeBitmap(String path, int maxWidth, int maxHeight) {
// 配置转换的信息
BitmapFactory.Options opts = new BitmapFactory.Options();
// 只解析宽高,不解析内容
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts); // 得到到像素信息是 null ,但是可以得到图像的实际宽高
// 分别计算宽度的比例和高度的比例
int w = (int) Math.ceil(opts.outWidth / maxWidth);
int h = (int) Math.ceil(opts.outHeight / maxHeight);
if (w > 1 || h > 1) {
// 该属性接收值必须要 >1 可以实现按照 1/opts.inSampleSize 的大小来解析该图片
opts.inSampleSize = w > h ? w : h;
}
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
return bitmap;
}
注意:最后要解析出像素信息必须要把 opts.inJustDecodeBounds 设置为 false 否则拿不到像素信息
public static void saveBitmap(Bitmap bitmap,String path){
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
// 保存 ( 压缩类型 , 压缩质量 , 输出流 )
bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null != out){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}