Android
主页 > 软件编程 > Android >

Android实现图片裁剪和上传的方法

2022-08-11 | F11站长开发者 | 点击:

具体内容如下

1、开发工具与关键技术:Eclipse、AndroidStudio
2、撰写时间:2020年06月18日

接着上一次,调用系统的相机。上一次,我们已经拿到了图片的uri。接下来,就要进行图片的裁剪和上传啦!其实图片的裁剪和上传比较简单。如何简单呢?好,我们来看代码。

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

1

2

3

4

//图像裁剪 , 需要先配置 maven { url "https://jitpack.io" }

implementation 'com.github.yalantis:ucrop:2.2.4'

//加载层 需要先配置 maven

implementation 'com.github.ForgetAll:LoadingDialog:v1.1.2'

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

1

2

3

4

<activity

    android:name="com.yalantis.ucrop.UCropActivity"

    android:screenOrientation="fullSensor"

    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

3、裁剪的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

//开始图片裁剪 使用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方法中调用裁剪的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

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、服务端的上传方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

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、效果图:

效果二:

原文链接:https://blog.csdn.net/weixin_43741599/article/details/106836462
相关文章
最新更新