Android如何实现图片裁剪和上传

发布时间:2022-08-12 10:56:59 作者:iii
来源:亿速云 阅读:286

本文小编为大家详细介绍“Android如何实现图片裁剪和上传”,内容详细,步骤清晰,细节处理妥当,希望这篇“Android如何实现图片裁剪和上传”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1、首先,配置maven,这里是使用uCrop裁剪图片

//图像裁剪 , 需要先配置 maven { url "https://jitpack.io" }
implementation 'com.github.yalantis:ucrop:2.2.4'
//加载层 需要先配置 maven
implementation 'com.github.ForgetAll:LoadingDialog:v1.1.2'

2、其次,在清单文件中添加。注意:fullSensor看个人的用法,有些版本太高,不可使用

<activity
    android:name="com.yalantis.ucrop.UCropActivity"
    android:screenOrientation="fullSensor"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

3、裁剪的方法

//开始图片裁剪 使用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);
    }

4、在上次的Activity方法中调用裁剪的方法

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();
        }
    }

5、服务端的上传方法

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);
    }

6、效果图:

Android如何实现图片裁剪和上传

效果二:

Android如何实现图片裁剪和上传

读到这里,这篇“Android如何实现图片裁剪和上传”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. android实现上传
  2. 如何使用JavaScript和canvas实现图片裁剪的功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android

上一篇:SQL数据分表MybatisPlus动态表名如何优化

下一篇:如何使用Cargo工具高效创建Rust项目

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》