图片剪裁 --高清图压缩 – Base64上传服务器
应用场景:
1、webview界面与native的js交互中调用更改头像
2、native的发布文章动态的添加多图
此处我的应用场景主要为一场景,用于js交互使用,但是我调用native的剪裁功能后发现剪裁图片时如果取消,无法获取取消的回调操作,而且还存在很多机型的适配和系统剪裁的方形或者圆形的适配
(比如:小米的data返回为null;华为手机默认剪裁为圆形,其他手机是方形;大图高清图压缩失败等等)
为了更好的适配各类其他系统和机型,我最终妥协了,选择一个三方的比较好的组件来完成这部分需求,你也可以借鉴下去完善它。
步骤:
一、Dialog或者PopupWindow来控制弹出拍照或相册
二、拍照或相册的操作后会有回调,此处我引入三方jar包完成后续操作
compile 'com.jph.takephoto:takephoto_library:4.1.0'
三、Base64位的数据处理并调用js来实现页面刷新和完成头像的加载
//注意:当前类需要是TakePhotoActivity的子类,否则无法实现下面方法
@Override
public void takeSuccess(TResult result) {//此方法是三方包中的回调成功返回的方法
super.takeSuccess(result);
pushCamera(result.getImages().get(0).getCompressPath());
}
private void pushCamera(String imagePath) {
//通过图片路径获取图片并压缩后转换成String
String encoded = bitmapToString(imagePath);
//下面这2句属于自己js的调用,你可以改成自己需要的样式,调用loadUrl即可
//String str = WebLoadUrlUtils.SplicingJsContext(WebLoadUrlUtils.actionFromAppWithImageCropperSuccess, encoded);
//WebLoadUrlUtils.loadJsUrl(WebLoadUrlUtils.actionFromAppWithImageCropperSuccess, str, webView);
}
//计算图片的缩放值
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
// 根据路径获得图片并压缩,返回bitmap用于显示
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
//把bitmap转换成String
public static String bitmapToString(String filePath) {
Bitmap bm = getSmallBitmap(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
注:引入的module中如果在裁剪时遇到裁剪框为圆形,则修改成如下:
if (Build.MANUFACTURER.equals("HUAWEI")) {
intent.putExtra("aspectX", 9998);
intent.putExtra("aspectY", 9999);
} else {
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
}