Android開發中如何實現頭像的更換與上傳

AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("添加圖片");
String[] items = { "選擇本地照片", "拍照" };
builder.setNegativeButton("取消", null);
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case CHOOSE_PICTURE: // 選擇本地照片
                Intent openAlbumIntent = new Intent(
                        Intent.ACTION_GET_CONTENT);
                openAlbumIntent.setType("image/*");
                //用startActivityForResult方法,待會兒重寫onActivityResult()方法,拿到圖片做裁剪操作
                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                break;
            case TAKE_PICTURE: // 拍照
                Intent openCameraIntent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                tempUri = Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "temp_image.jpg"));
                // 將拍照所得的相片保存到SD卡根目錄
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                break;
        }
    }
});
builder.show();

/** * 上傳服務器 * @param mobile * @param file */ public void touimg(String mobile, File file){ Map params=new HashMap<>(); params.put("uid",mobile); OkHttpClient okHttpClient=new OkHttpClient(); MultipartBody.Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM); RequestBody requestBody=RequestBody.create(MediaType.parse("image/*"),file); builder.addFormDataPart("file",file.getName(),requestBody); if(params!=null){ for (Map.Entry entry : params.entrySet()) { builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue())); } Request request=new Request.Builder().url(Api.ICONIMG_API).post(builder.build()).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("=======失敗瞭==="); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("=======成功瞭==="); } }); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == MainActivity.RESULT_OK) { switch (requestCode) { case TAKE_PICTURE: cutImage(tempUri); // 對圖片進行裁剪處理 拍照 break; case CHOOSE_PICTURE: cutImage(data.getData()); // 對圖片進行裁剪處理 break; case CROP_SMALL_PICTURE: if (data != null) { try { setImageToView(data); // 讓剛才選擇裁剪得到的圖片顯示在界面上 } catch (IOException e) { e.printStackTrace(); } } break; } } } /** * 裁剪圖片方法實現 */ protected void cutImage(Uri uri) { if (uri == null) { Log.i("alanjet", "The uri is not exist."); } tempUri = uri; Intent intent = new Intent("com.android.camera.action.CROP"); //com.android.camera.action.CROP這個action是用來裁剪圖片用的 intent.setDataAndType(uri, "image/*"); // 設置裁剪 intent.putExtra("crop", "true"); // aspectX aspectY 是寬高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪圖片寬高 intent.putExtra("outputX", 150); intent.putExtra("outputY", 150); intent.putExtra("return-data", true); startActivityForResult(intent, CROP_SMALL_PICTURE); } /** * 保存裁剪之後的圖片數據 */ protected void setImageToView(Intent data) throws IOException { Bundle extras = data.getExtras(); if (extras != null) { mBitmap = extras.getParcelable("data"); //這裡圖片是方形的,可以用一個工具類處理成圓形(很多頭像都是圓形,這種工具類網上很多不再詳述) System.out.println("============="+mBitmap.toString()); saveFile(mBitmap,"icon_bai.jpg");//存到本地 System.out.println("dianjial"); iv_icon.setImageBitmap(mBitmap);//顯示圖片 } } /** * bitmap 轉換成file文件 .jpeg * @param bm * @param fileName * @throws IOException */ public void saveFile(Bitmap bm, String fileName) throws IOException { String path = getSDPath() +"/revoeyee/"; File dirFile = new File(path); if(!dirFile.exists()){ dirFile.mkdir(); } File myCaptureFile = new File(path + fileName); //bitmip 保存到本地緩存 //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); FileOutputStream bos=new FileOutputStream(myCaptureFile); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); touimg(uid,myCaptureFile); /** * 上傳服務器 */ // HashMap map=new HashMap<>(); // map.put("mobile",name); // post_file(Api.ICONIMG_API,map,myCaptureFile); bos.flush(); bos.close(); } /** * 獲取路徑 * @return */ public static String getSDPath(){ File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判斷sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();//獲取跟目錄 } return sdDir.toString(); } public void btn_user_tiaozhuan(View v){ startActivity(new Intent(this,SousuoActivity.class)); }

You May Also Like