注册

Android 中bitmap的处理:获取缩略图,点击查看大图

最近在忙的demo里面,涉及到身份证照片上传的问题,一个页面三个图片的布局,同时还有其他按钮等,导致图片显示的地方很小,所以大图会放不下,无法正常显示。之前一直在纠结怎么压缩bitmap使得不管是大小还是质量压缩之后,app和后台都能看到清晰的图片。后来发现,其实可以直接app显示的时候,显示缩略图,但是上传到后台的时候,还是上传原来路径下的未压缩的图片信息。其实还可以加上,ImageView的点击事件查看详细的图片。具体看需求。

通过路径获取Bitmap的缩略图
public Bitmap getBitmapByWidth(String localImagePath, int width, int addedScaling) {
if (TextUtils.isEmpty(localImagePath)) {
return null;
}

Bitmap temBitmap = null;

try {
BitmapFactory.Options outOptions = new BitmapFactory.Options();

// 设置该属性为true,不加载图片到内存,只返回图片的宽高到options中。
outOptions.inJustDecodeBounds = true;

// 加载获取图片的宽高
BitmapFactory.decodeFile(localImagePath, outOptions);

int height = outOptions.outHeight;

if (outOptions.outWidth > width) {
// 根据宽设置缩放比例
outOptions.inSampleSize = outOptions.outWidth / width + 1 + addedScaling;
outOptions.outWidth = width;

// 计算缩放后的高度
height = outOptions.outHeight / outOptions.inSampleSize;
outOptions.outHeight = height;
}

// 重新设置该属性为false,加载图片返回
outOptions.inJustDecodeBounds = false;
temBitmap = BitmapFactory.decodeFile(localImagePath, outOptions);
} catch (Throwable t) {
t.printStackTrace();
}

return temBitmap;
}
同时,参数里面的路径也可以改为Bitmap,看自己需要吧。

点击缩略图显示完整的图片

设置ImageView的点击事件,看具体想怎么处理,如果点击换其他图片,则直接跳转,如果是点击查看详细图片,则弹出PopupWindow,里面放一张ImageView,通过传过去的参数filePath,直接显示原来没压缩的图片即可。这个简单就不贴代码了。

Bitmap的旋转

自己的demo里面,图片长宽不一,缩略图肯定是宽大于长的,而详细信息里面或者手机相册里面的图一般都是长大于宽,所以涉及到图片旋转的问题了。
  public Bitmap getRotateBitmap(int type, String bitmapPath) { // type 1
// 竖屏显示图片,2
// 横屏显示图片

Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);

Bitmap resultBitmap = bitmap;
int height = bitmap.getHeight();
int width = bitmap.getWidth();

System.out.println("获取的bitmap 宽和高:" + width + ":" + height);

switch (type) {
case 1: // 竖屏显示图片,需要偏高
if (height < width) {
// 如果长度小于宽度,则需要选择,否则不需要旋转,只要将option修改即可
Matrix mmMatrix = new Matrix();
mmMatrix.postRotate(90f);

resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
}

break;
case 2: // 横屏显示图片,需要偏长
if (height > width) {
// 如果宽度小于长度
Matrix mmMatrix = new Matrix();
mmMatrix.postRotate(90f);

resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
}

break;

default:
break;
}

return resultBitmap;

}

 
本篇文章由热心开发者提供,作者主页Mudo_Yan

0 个评论

要回复文章请先登录注册