Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

聯絡人頭像實作:拍照、相冊、裁剪與上傳的完整流程

編輯:關於 Android 程式設計

點一下頭像,從底部彈出「拍照 / 相冊 / 取消」,選完再裁成正方形、存到本機、最後上傳伺服器——這是聯絡人編輯頁最常見的互動。以下把各環節拆開說明。

一、觸發:用 PopupWindow 做底部選單

icon = (ImageView) findViewById(R.id.icon);
icon.setBackgroundResource(R.drawable.icos6);

icon.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        View popupWview = getLayoutInflater().inflate(R.layout.activity_getPhoto, null);

        final PopupWindow alert = new PopupWindow(popupWview,
                display.getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        alert.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        alert.setFocusable(true);   // 不設 this,返回鍵不會被攔下

        // 攔截返回鍵以關閉彈窗
        popupWview.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && keyCode == KeyEvent.KEYCODE_BACK) {
                    alert.dismiss();
                    return true;
                }
                return false;
            }
        });

        // 拍照
        Button paizhao = (Button) popupWview.findViewById(R.id.paizhao);
        paizhao.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File out = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
                    startActivityForResult(intent, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                alert.dismiss();
            }
        });

        // 相冊
        Button xiangce = (Button) popupWview.findViewById(R.id.xiangce);
        xiangce.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 2);
                alert.dismiss();
            }
        });

        // 取消
        Button quxiao = (Button) popupWview.findViewById(R.id.quxiao);
        quxiao.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                alert.dismiss();
            }
        });
    }
});

這裡有個細節值得留意:原範例把返回鍵監聽掛在 touxiang 這個 LinearLayout 上,是不會生效的——只有可取得焦點的元件才會收到按鍵事件,普通 LinearLayout 並不適合。上面改為掛在 popupWview 根視圖,並搭配 setFocusable(true),才是可行寫法。

二、進頁面時先還原上次的頭像

File dir = new File(Environment.getExternalStorageDirectory() + "/photo/icon/");
if (!dir.exists()) {
    dir.mkdirs();
}

try {
    File myCaptureFile = new File(dir, "friend.jpg");
    if (myCaptureFile.exists()) {
        Bitmap bitmap = BitmapFactory.decodeFile(myCaptureFile.getAbsolutePath());
        icon.setImageBitmap(bitmap);
    } else {
        icon.setImageResource(R.drawable.icos6);   // 預設頭像
    }
} catch (Exception e) {
    e.printStackTrace();
}

// 若伺服器端已有頭像記錄,背景執行緒去抓回來
new asynicon().execute();

三、裁剪:呼叫系統的 CROP 動作

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == 0) {          // 來自拍照
            File file = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
            Uri uri = Uri.fromFile(file);
            startCrop(uri);
            return;
        }
        if (requestCode == 2) {          // 來自相冊
            startCrop(data.getData());
            return;
        }
        if (requestCode == 3) {          // 裁剪結果
            if (data != null) {
                setPicToView(data);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void startCrop(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);      // 寬高比
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 150);    // 輸出的實際尺寸
    intent.putExtra("outputY", 150);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 3);
}

把兩個來源各自的裁剪邏輯抽成 startCrop(),是因為它們除了 Uri 來源不同,其餘參數完全一致。原範例複製貼上兩遍,日後要改尺寸時很容易漏改一處。

四、把結果存成本機檔案

private void setPicToView(Intent picdata) {
    Bundle extras = picdata.getExtras();
    if (extras == null) {
        return;
    }
    Bitmap photo = extras.getParcelable("data");

    File target = new File(Environment.getExternalStorageDirectory()
            + "/photo/icon/friend.jpg");
    BufferedOutputStream bos = null;
    try {
        if (target.exists()) {
            target.delete();
        }
        target.createNewFile();
        bos = new BufferedOutputStream(new FileOutputStream(target));
        photo.compress(Bitmap.CompressFormat.JPEG, 80, bos);   // 品質 80
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    icon.setImageBitmap(photo);
    new Asyn().execute();   // 接著上傳
}

五、上傳:multipart/form-data

public String uploadFile(String actionUrl, String fileName, File uploadFile) {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    StringBuilder sb = new StringBuilder();

    try {
        URL url = new URL(actionUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setUseCaches(false);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Charset", "utf-8");
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + end);
        dos.writeBytes("Content-Disposition: form-data; "
                + "name=\"file\";filename=\"" + fileName + "\"" + end);
        dos.writeBytes(end);

        FileInputStream fis = new FileInputStream(uploadFile);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, length);
        }
        fis.close();

        dos.writeBytes(end);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
        dos.flush();
        dos.close();

        BufferedReader read = new BufferedReader(
                new InputStreamReader(httpConn.getInputStream(), "utf-8"));
        String line;
        while ((line = read.readLine()) != null) {
            sb.append(line);
        }
        read.close();
        return sb.toString().trim();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

網路結果用 AsyncTask 解析並更新介面:

public class Asyn extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... params) {
        File myCapture = new File(Environment.getExternalStorageDirectory()
                + "/photo/icon/friend.jpg");
        String str = uploadFile("https://your.server/ace.php", "friend.jpg", myCapture);
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject json = new JSONObject(str);
            int stateCode = json.getInt("State_code");
            if (stateCode == 1) {
                publishProgress(1);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

六、從網路載入頭像

public void myface(String face) {
    try {
        URL url = new URL("https://your.server/" + face);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.connect();
        InputStream in = con.getInputStream();
        bit = BitmapFactory.decodeStream(in);
        // 同樣以 JPEG 品質 80 存回本機,行為與 setPicToView 相同
    } catch (Exception e) {
        e.printStackTrace();
    }
}

這份程式碼上線前該修正的事

儲存路徑。 硬寫 /sdcard/... 在 Android 4.4 之後逐漸失效,Android 10 的分區儲存更完全封死了這種寫法。請改用 getExternalFilesDir() 取得應用私有目錄,或透過 MediaStore 寫入公共媒體庫。

注意原範例的路徑不一致。 部分段落寫 /photo/icon/,另一段卻寫 /vpn/icon/,這會導致上傳時找不到檔案。這類字串重複出現的情境,正適合成為常數集中管理。

Uri 與檔案格式。 Uri.fromFile() 在 Android 7.0 以上會觸發 FileUriExposedException,必須改用 FileProvider.getUriForFile() 並在 Manifest 中宣告對應的 paths 設定。

裁剪 Intent 並非標準 API。 com.android.camera.action.CROP 是各家 ROM 的私有實作,在部分機型上完全不存在,會直接丟出 ActivityNotFoundException。若要穩定支援,建議自行以 Bitmap + Matrix 或第三方裁剪函式庫(如 UCrop)實作。

記憶體風險。 BitmapFactory.decodeStream() 不指定 inSampleSize,遇到高解析度照片時很容易 OOM。上傳前也應先縮圖,同時能省下可觀的流量。

上傳介面缺少驗證。 原範例的 URL 直接帶著身分碼走 query string,且全程使用明文 HTTP。真實環境應改用 HTTPS,並把憑證放在請求標頭或 body 中,避免被中間人攔截。

最後,若只是想完成「選一張圖當頭像」這個需求,AndroidX 的 Activity Result API 搭配 PickVisualMedia 或 TakePicture 契約,再配上 Coil/Glide 處理顯示與上傳,代碼量會比上面少一個數量級,相容性也好得多。理解上述手刻流程的意義,在於當函式庫的行為不如預期時,你知道底層實際發生了什麼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved