溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android如何實現(xiàn)圖片裁剪和上傳

發(fā)布時間:2022-08-12 10:56:59 來源:億速云 閱讀:286 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“Android如何實現(xiàn)圖片裁剪和上傳”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Android如何實現(xiàn)圖片裁剪和上傳”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

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();
        //設(shè)置裁剪圖片可操作的手勢
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //是否能調(diào)整裁剪框
        options.setFreeStyleCropEnabled(false);
        uCrop.withOptions(options);
        //設(shè)置比例為1:1
        uCrop.withAspectRatio(1, 1);
        //注意!?。?!Fragment中使用uCrop 必須這樣,否則Fragment的onActivityResult接收不到回調(diào)
        uCrop.start(mActivityContext, this);
    }

4、在上次的Activity方法中調(diào)用裁剪的方法

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;//存放相機(jī)的圖片
    private File mCropFile;//存放圖像裁剪的圖片
private LoadingDialog loadingDialog;//加載層
**//注意:這個方法里面有些代碼是上次的系統(tǒng)調(diào)用相機(jī)的,請留意和上次代碼是否有重復(fù)**
@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());
                    **//進(jìn)行圖像裁剪 這里需要調(diào)用圖片裁剪的方法**
                    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創(chuàng)建一個content類型的Uri
                       Uri dataUri = FileProvider.getUriForFile(mActivityContext, "com.gx.reservation.fileprovider", imgFile);
                        Log.e("ImagUri", dataUri.getPath());
                        **//進(jìn)行圖像裁剪 這里需要調(diào)用圖片裁剪的方法**
                        startPhotoZoom(dataUri);
                    } else {
                        Toast.makeText(mActivityContext, "選擇圖片失敗", Toast.LENGTH_SHORT).show();
                    }
                    break;
**//這個還算比較重要的代碼**
                case CAMERA_REQUEST_CODE://相機(jī)的返回
                    Uri inputUrl;
                    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                        //Android7.0及以上
                        //通過FileProvider創(chuàng)建一個content類型的Uri                     inputUrl=FileProvider.getUriForFile(mActivityContext,"com.gx.reservation.fileprovider",mCameraFile);
                    }else {
                        //Android7.0以下
                        inputUrl=Uri.fromFile(mCameraFile);
                    }
                    //啟動圖片裁剪
                    if (inputUrl!=null){
                        startPhotoZoom(inputUrl);
                    }
                    break;
**//核心代碼,其他的代碼上次調(diào)用系統(tǒng)的相機(jī)都有用到**
                case UCrop.REQUEST_CROP://Ucrop裁剪返回
                    Uri resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        //uri轉(zhuǎn)文件路徑
                        String strPathCrop = GetImagePath.getPath(mActivityContext, resultUri);
                        if (Tools.isNotNull(strPathCrop)) {
                            File fileUp = new File(strPathCrop);
                            if (fileUp.exists()) {
                                //=====上傳文件
                                String url = ServiceUrls.getMemberMethodUrl("uploadMemberPicture");
                                //參數(shù)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();
                                //發(fā)送請求
                    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() {
                                                //關(guān)閉加載層
                                                loadingDialog.close();
                                    String strText = "網(wǎng)絡(luò)環(huán)境不佳,請稍后再試";
                                          if (isSuccess && responseCode == 200) {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.getInt("code");
                         strText = jsonObject.getString("text");
                                                        if (code == 200) {
//提示:這里我是用戶的信息的修改,所以把修改后的數(shù)據(jù)設(shè)置到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、服務(wù)端的上傳方法

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();
                    //獲取文件擴(kuò)展名稱
                    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();
                            }
                        }
                        //將頭像的文件名稱保存的數(shù)據(jù)庫
                        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("參數(shù)異常");
                }
            }else {
                jsonReturn.setCode(500);
                jsonReturn.setText("參數(shù)異常");
            }
        }else {
            jsonReturn.setCode(500);
            jsonReturn.setText("上傳的頭像為空");
        }
        return gson.toJson(jsonReturn);
    }

6、效果圖:

Android如何實現(xiàn)圖片裁剪和上傳

效果二:

Android如何實現(xiàn)圖片裁剪和上傳

讀到這里,這篇“Android如何實現(xiàn)圖片裁剪和上傳”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI