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

Android 圖片全流程:相冊選圖、相機拍照、裁剪與上傳服務器

編輯:關於 Android 開發

Android 圖片全流程:相冊選圖、相機拍照、裁剪與上傳服務器

頭像上傳是幾乎每個應用都會碰到的需求,但完整走一遍——從相冊選或直接拍照,到裁剪,再到上傳——中間的坑並不少。這篇把整個鏈路串起來記錄一下。

一、調用相機拍照

用 MediaStore.ACTION_IMAGE_CAPTURE 跳轉到拍照界面,並通過 EXTRA_OUTPUT 指定照片的存放路徑。這裡用時間戳命名,避免覆蓋:

Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mSzImageFileName)));
startActivityForResult(takeIntent, REQUEST_TAKE_PHOTO);

二、從相冊選圖

Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
// 如果要限制上傳到服務器的圖片類型,可以直接寫 image/jpeg、image/png 等
pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, REQUEST_PICK_PHOTO);

三、接收返回結果

不論從相冊還是相機回來,都在 onActivityResult 裡分流處理:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_PICK_PHOTO: // 直接從相冊獲取
            try {
                startPhotoZoom(data.getData()); // 跳轉到裁剪界面
            } catch (NullPointerException e) {
                e.printStackTrace(); // 用戶點擊了取消
            }
            break;

        case REQUEST_TAKE_PHOTO: // 調用相機拍照
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    File temp = new File(Environment.getExternalStorageDirectory(), mSzImageFileName);
                    if (temp.exists()) {
                        startPhotoZoom(Uri.fromFile(temp));
                    }
                }
            }, 1000);
            break;

        case REQUEST_CUT_PHOTO: // 取得裁剪後的圖片
            if (data != null) {
                setPicToView(data); // 保存和上傳圖片
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

拍照這裡延遲一秒再讀文件,是因為部分機型寫檔有延遲,立刻去取會拿到不存在或寫了一半的文件。這算是個不太優雅但實用的妥協。

四、裁剪圖片

調用系統自帶的裁剪 Activity 即可,關鍵是幾個比例與尺寸的 extras:

/**
 * 裁剪圖片方法實現
 */
private void startPhotoZoom(Uri uri) {
    if (uri != null) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop=true 表示在開啟的 Intent 中顯示可裁剪的 VIEW
        intent.putExtra("crop", "true");
        // aspectX / aspectY 是寬高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX / outputY 是裁剪後圖片的寬高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CUT_PHOTO);
    }
}

五、保存並上傳

/**
 * 保存裁剪之後的圖片數據
 */
private void setPicToView(Intent picdata) {
    Bundle extras = picdata.getExtras();
    if (extras != null) {
        Bitmap photo = extras.getParcelable("data");
        mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";
        mImgUrlPath = Environment.getExternalStorageDirectory() + File.separator
                + "cut_image" + File.separator + mSzImageFileName;
        try {
            NetUtil.saveBitmapToFile(photo, mImgUrlPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 新線程後台上傳服務端
        new Thread(uploadImageRunnable).start();
    }
}

上傳放在獨立線程裡,避免網絡操作阻塞主線程:

Runnable uploadImageRunnable = new Runnable() {
    @Override
    public void run() {
        Map<String, String> params = new HashMap<>();
        params.put("mid", mSzId); // 上傳參數

        Map<String, File> files = new HashMap<>();
        files.put("myUpload", new File(mImgUrlPath)); // 上傳文件路徑

        try {
            String json = NetUtil.uploadFile(Constants.URL_EDIT_IMG, params, files);
            // json 為服務器返回的數據,可自行解析取得需要的字段
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

六、NetUtil 工具類

這裡用 HttpURLConnection 手工拼 multipart/form-data 請求體,好處是不依賴任何第三方庫,也便於看清協議細節:

public class NetUtil {

    // 上傳圖片到服務器
    public static String uploadFile(String url, Map<String, String> params,
                                    Map<String, File> files) throws IOException {
        String result = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FORM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";

        HttpURLConnection conn = null;
        try {
            URL uri = new URL(url);
            conn = (HttpURLConnection) uri.openConnection();
            conn.setReadTimeout(10 * 1000);
            conn.setDoInput(true);   // 允許輸入
            conn.setDoOutput(true);  // 允許輸出
            conn.setUseCaches(false); // 不使用緩存
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Charset", CHARSET);
            conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);

            // 首先組拼文本類型的參數
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFIX).append(BOUNDARY).append(LINEND);
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
                sb.append(LINEND);
                sb.append(entry.getValue());
                sb.append(LINEND);
            }

            DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
            outStream.write(sb.toString().getBytes());

            // 發送文件數據
            if (files != null) {
                for (Map.Entry<String, File> file : files.entrySet()) {
                    StringBuilder sb1 = new StringBuilder();
                    sb1.append(PREFIX).append(BOUNDARY).append(LINEND);
                    sb1.append("Content-Disposition: form-data; name=\"" + file.getKey()
                            + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND);
                    sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                    sb1.append(LINEND);
                    outStream.write(sb1.toString().getBytes());

                    InputStream is = new FileInputStream(file.getValue());
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    is.close();
                    outStream.write(LINEND.getBytes());
                }
            }

            // 請求結束標志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
            outStream.write(end_data);
            outStream.flush();
            outStream.close();

            // 讀取響應
            StringBuilder sb2 = new StringBuilder();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), CHARSET));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb2.append(inputLine);
            }
            in.close();
            result = sb2.toString();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }

    /**
     * 保存圖片到 SD 卡
     */
    public static void saveBitmapToFile(Bitmap bitmap, String _file) throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            File filePath = new File(_file.substring(0, end));
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }
}

拼 multipart 時有幾個細節容易出錯:boundary 必須與 Content-Type 裡聲明的一致;每個分段之間、以及頭部與主體之間都要空一行(也就是連續兩個 \r\n);最後要用 --boundary-- 作結束標志。少一個換行,服務器就會一直等下去。

如果這個流程要放到今天的項目裡,更省事的選擇是直接用 OkHttp 的 MultipartBody 或 Retrofit,能省掉上面這一整段拼包的代碼。這裡手工實現主要是為了記錄協議本身長什麼樣子。

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