1、开发工具与关键技术:Eclipse、AndroidStudio
2、撰写时间:2020年06月18日
接着上一次,调用系统的相机。上一次,我们已经拿到了图片的uri。接下来,就要进行图片的裁剪和上传啦!其实图片的裁剪和上传比较简单。如何简单呢?好,我们来看代码。
//图像裁剪 , 需要先配置 maven { url "https://jitpack.io" }
implementation 'com.github.yalantis:ucrop:2.2.4'
//加载层 需要先配置 maven
implementation 'com.github.ForgetAll:LoadingDialog:v1.1.2'
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="fullSensor"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
//开始图片裁剪 使用UCrop
private void startPhotoZoom(Uri uri) {
//裁剪后保存到文件中
Uri cropFileUri = Uri.fromFile(mCropFile);
UCrop uCrop = UCrop.of(uri, cropFileUri);//源文件url,裁剪后输出文件uri
UCrop.Options options = new UCrop.Options();
//设置裁剪图片可操作的手势
options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
//是否能调整裁剪框
options.setFreeStyleCropEnabled(false);
uCrop.withOptions(options);
//设置比例为1:1
uCrop.withAspectRatio(1, 1);
//注意!!!!Fragment中使用uCrop 必须这样,否则Fragment的onActivityResult接收不到回调
uCrop.start(mActivityContext, this);
}
public class UserFragment extends Fragment {
private static final int IMAGE_REQUEST_CODE = 100;
private static final int IMAGE_REQUEST_CODE_GE7 = 101;
private static final int CAMERA_REQUEST_CODE = 104;
private static final int REQUEST_EXTERNAL_STORAGE_CODE = 200;
private Activity mActivityContext;//获取上下文
private MyApplication myApplication;//获取myApplication中的BestLogin对象
private BestLogin member;//用户对象
private File mGalleryFile;//存放图库选择是返回的图片
private File mCameraFile;//存放相机的图片
private File mCropFile;//存放图像裁剪的图片
private LoadingDialog loadingDialog;//加载层
**//注意:这个方法里面有些代码是上次的系统调用相机的,请留意和上次代码是否有重复**
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && (data != null || requestCode == CAMERA_REQUEST_CODE)) {
switch (requestCode) {
case IMAGE_REQUEST_CODE://版本<7.0 图库返回
//获取图片的全路径
Uri uri = data.getData();
Log.e("ImagUri", uri.getPath());
**//进行图像裁剪 这里需要调用图片裁剪的方法**
startPhotoZoom(uri);
break;
case IMAGE_REQUEST_CODE_GE7://版本>= 7.0 图库返回
//获取文件路径
String strPath = GetImagePath.getPath(mActivityContext, data.getData());
if (Tools.isNotNull(strPath)) {
File imgFile = new File(strPath);
//通过FileProvider创建一个content类型的Uri
Uri dataUri = FileProvider.getUriForFile(mActivityContext, "com.gx.reservation.fileprovider", imgFile);
Log.e("ImagUri", dataUri.getPath());
**//进行图像裁剪 这里需要调用图片裁剪的方法**
startPhotoZoom(dataUri);
} else {
Toast.makeText(mActivityContext, "选择图片失败", Toast.LENGTH_SHORT).show();
}
break;
**//这个还算比较重要的代码**
case CAMERA_REQUEST_CODE://相机的返回
Uri inputUrl;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
//Android7.0及以上
//通过FileProvider创建一个content类型的Uri inputUrl=FileProvider.getUriForFile(mActivityContext,"com.gx.reservation.fileprovider",mCameraFile);
}else {
//Android7.0以下
inputUrl=Uri.fromFile(mCameraFile);
}
//启动图片裁剪
if (inputUrl!=null){
startPhotoZoom(inputUrl);
}
break;
**//核心代码,其他的代码上次调用系统的相机都有用到**
case UCrop.REQUEST_CROP://Ucrop裁剪返回
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
//uri转文件路径
String strPathCrop = GetImagePath.getPath(mActivityContext, resultUri);
if (Tools.isNotNull(strPathCrop)) {
File fileUp = new File(strPathCrop);
if (fileUp.exists()) {
//=====上传文件
String url = ServiceUrls.getMemberMethodUrl("uploadMemberPicture");
//参数map
Map<String, Object> pMap = new HashMap<>();
pMap.put("memberId", myApplication.getBestlogin().getLoginid());
//文件map
Map<String, File> fileMap = new HashMap<>();
fileMap.put("photo", fileUp);
//显示加载层
loadingDialog.setLoadingText("上传中...").show();
//发送请求
OkHttpTool.httpPostWithFile(url, pMap, fileMap, new OkHttpTool.ResponseCallback() {
@Override
public void onResponse(final boolean isSuccess, final int responseCode, String response, Exception exception) {
mActivityContext.runOnUiThread(new Runnable() {
@Override
public void run() {
//关闭加载层
loadingDialog.close();
String strText = "网络环境不佳,请稍后再试";
if (isSuccess && responseCode == 200) {
try {
JSONObject jsonObject = new JSONObject(response);
int code = jsonObject.getInt("code");
strText = jsonObject.getString("text");
if (code == 200) {
//提示:这里我是用户的信息的修改,所以把修改后的数据设置到BestLogin对象中
String strData = jsonObject.getString("data");
BestLogin newMember = gson.fromJson(strData, BestLogin.class);
if (newMember != null) { myApplication.setBestlogin(newMember);
//重新加载本页面
initView();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
}
});
}
});
return;
}
}
}
Toast.makeText(mActivityContext, "图片裁剪失败", Toast.LENGTH_SHORT).show();
break;
}
} else {
Toast.makeText(mActivityContext, "操作失败", Toast.LENGTH_SHORT).show();
}
}
public Object uploadMemberPicture(int memberId, @RequestParam(value = "photo") MultipartFile mPhoto) {
JsonReturn jsonReturn=new JsonReturn();
if(!mPhoto.isEmpty() && mPhoto.getSize()>0) {//判断文件是否为空
if(memberId>0) {//判断memberid
BestLogin member=this.appMemberService.selectMemberById(memberId);
if(member!=null) {
//获取文件名称
String fileName=mPhoto.getOriginalFilename();
//获取文件扩展名称
String strExt=fileName.substring(fileName.lastIndexOf('.'));
String phoneName=memberId + "_" + System.currentTimeMillis() + "_" + System.nanoTime() + strExt;
//保存图片
try {
FileUtils.writeByteArrayToFile(new File(AppSeting.UPLOAD_MEMBER_PHOTO_DIR, phoneName),mPhoto.getBytes());
//删除以前的图片
if(Tools.isNotNull(member.getPhoto())) {
File oldImage=new File(AppSeting.UPLOAD_MEMBER_PHOTO_DIR,member.getPhoto());
if(oldImage.exists()) {
oldImage.delete();
}
}
//将头像的文件名称保存的数据库
member.setPhoto(phoneName);
int intR=this.appMemberService.updateMemberById(member);
if(intR>0) {
BestLogin memberVo=this.appMemberService.findMemberById(memberId);
jsonReturn.setCode(200);
jsonReturn.setText("头像上传成功");
jsonReturn.setData(memberVo);
}else {
jsonReturn.setCode(300);
jsonReturn.setText("头像上传失败,稍后再试");
}
} catch (IOException e) {
e.printStackTrace();
jsonReturn.setCode(300);
jsonReturn.setText("头像上传失败,稍后再试");
}
}else {
jsonReturn.setCode(500);
jsonReturn.setText("参数异常");
}
}else {
jsonReturn.setCode(500);
jsonReturn.setText("参数异常");
}
}else {
jsonReturn.setCode(500);
jsonReturn.setText("上传的头像为空");
}
return gson.toJson(jsonReturn);
}