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

Android 拍照、上傳與顯示圖片:從 Camera 到 Base64 + JSON 的完整流程

編輯:關於 Android 程式設計

做過 UGC 類的 App 大概都躲不掉這條路:叫起相機拍照 → 存到本機 → 壓縮編碼 → POST 上傳 → 再把圖片抓回來顯示。以下把整個環節拆成四段來說明。

一、按下「拍照」:先檢查環境,再準備檔名

拍照前一定要確認外部儲存空間可用,並預先建立好存放資料夾。檔名建議用時間戳記產生,可避免覆寫:

protected void takePhoto() {
    String sdStatus = Environment.getExternalStorageState();
    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
        // 檢測 SD 是否可用
        Log.i("exception", "SD card is not avaiable/writeable right now.");
        Toast.makeText(getApplicationContext(), "sd卡無法使用", Toast.LENGTH_SHORT).show();
        return;
    }

    File file = new File(
            Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "myAQ" + File.separator);
    if (!file.exists())
        file.mkdirs(); // 創建文件夾

    String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    fileName = time + ".jpg";

    Intent intent = new Intent(PublishNewsActivity.this, TakePhotoActivity.class);
    intent.putExtra("fileName", fileName);
    startActivityForResult(intent, 10);
}

用 startActivityForResult() 而非 startActivity(),是因為拍照後我們需要回到這個頁面把縮圖顯示出來。順帶一提,別忘了在 AndroidManifest.xml 補上 CAMERA 與 WRITE_EXTERNAL_STORAGE 的權限宣告,同時在 TakePhotoActivity 加上 android:screenOrientation="landscape" 之類的設定,避免預覽畫面被強制轉屏。

二、TakePhotoActivity:相機預覽與抓拍

這個 Activity 負責開啟硬體相機、把預覽畫面綁到 SurfaceView 上,並在按下快門後把 JPEG 資料寫檔。

public class TakePhotoActivity extends Activity {

    private SurfaceView mSurfaceView;
    private SurfaceHolder mHolder;
    protected Camera camera;
    private Button start;
    private String photoName;
    private int window_width;
    private int window_height;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        requestWindowFeature(Window.FEATURE_NO_TITLE);          // 沒有標題
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);    // 設置全屏
        getWindow().setFormat(PixelFormat.TRANSLUCENT);          // 設置半透明
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 設置高亮
        setContentView(R.layout.activity_take_photo);

        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        window_width = dm.widthPixels;   // 屏幕寬度
        window_height = dm.heightPixels; // 屏幕高度

        start = (Button) findViewById(R.id.take_picture_Button);

        mSurfaceView = (SurfaceView) findViewById(R.id.takePicture_surfaceview); // 初始預覽窗口
        photoName = (String) (this.getIntent().getExtras().getString("fileName"));

        // 依 4:3 比例計算預覽畫面尺寸並水平居中
        LinearLayout.LayoutParams param =
                new LinearLayout.LayoutParams(window_height * 4 / 3, window_height);
        param.leftMargin = (window_width - param.width) / 2;
        mSurfaceView.setLayoutParams(param);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startShot();
            }
        });

        // 綁定初始預覽視圖
        mHolder = mSurfaceView.getHolder();
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHolder.addCallback(new Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                camera.stopPreview();
                camera.release();
                camera = null;      // 記得釋放
                mSurfaceView = null;
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    camera = Camera.open();
                    Camera.Parameters parameters = camera.getParameters();
                    parameters.setPreviewFrameRate(24);        // 每秒 24 幀
                    parameters.setPictureSize(640, 480);
                    parameters.setPictureFormat(ImageFormat.JPEG); // 設置照片的輸出格式
                    parameters.set("jpeg-quality", 100);       // 照片質量
                    parameters.setPreviewSize(640, 480);
                    camera.setParameters(parameters);
                    camera.setPreviewDisplay(holder);
                    camera.startPreview();
                } catch (Exception e) {
                    camera.release();
                    Log.i("why", e.getMessage());
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                                       int width, int height) { }
        });
    }

    protected void startShot() {
        if (camera != null) {
            camera.autoFocus(null);
            camera.takePicture(null, null, callback);
        }
    }

    PictureCallback callback = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            Matrix matrix = new Matrix();
            matrix.postScale(1f, 1f);   // 這裡可視需要調整縮放或旋轉
            bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            String shot_path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "myAQ" + File.separator;
            String shot_fileName = photoName;
            File shot_out = new File(shot_path);
            if (!shot_out.exists()) {
                shot_out.mkdirs();
            }
            shot_out = new File(shot_path, shot_fileName);
            try {
                FileOutputStream outStream = new FileOutputStream(shot_out);
                bitmap.compress(CompressFormat.JPEG, 90, outStream);
                outStream.close();

                Intent i = new Intent();
                setResult(RESULT_OK, i);
                TakePhotoActivity.this.finish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

SurfaceHolder 的 callback 裡有個常被忽略的重點:surfaceDestroyed() 一定要 stopPreview() 再 release(),否則相機資源不會交還給系統,第二次進入就會拿到「camera could not be opened」的錯誤。

三、回到上一頁:把拍好的照片顯示出來

在呼叫拍照的那個 Activity 覆寫 onActivityResult,用 BitmapFactory.decodeFile() 直接從路徑讀回來貼到 ImageView:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        ImageView imageView = (ImageView) findViewById(R.id.publish_imageview);
        picPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "myAQ" + File.separator + fileName;
        imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));
    }
}

四、上傳:Base64 編碼後包成一個 JSONObject

這一段有個關鍵設計:先把所有欄位(包含圖片的 Base64 字串)全部塞進同一個 JSONObject,再將這個 JSONObject 序列化後放進 NameValuePair 送出。這樣做的好處是請求本體只有一個參數,JSON 結構也更輕量級。

(原本嘗試把編碼後的長字串直接當成獨立參數塞進 nameValuePairs,結果出了問題但一時找不出原因,於是改採這個折衷方案,實測穩定。)

protected void publish_news() {
    ArrayList<String> paraName = new ArrayList<String>();
    ArrayList<String> paraValue = new ArrayList<String>();

    EditText publish_newstitle = (EditText) findViewById(R.id.publish_newstitle);
    if (publish_newstitle.getText() == null
            || publish_newstitle.getText().toString().trim().equals("")) {
        publish_newstitle.setError("請填寫新聞標題");
        publish_newstitle.requestFocus();
        return;
    }

    EditText publish_newscontent = (EditText) findViewById(R.id.publish_newscontent);
    if (publish_newscontent.getText() == null
            || publish_newscontent.getText().toString().trim().equals("")) {
        publish_newscontent.setError("請填寫新聞內容");
        publish_newscontent.requestFocus();
        return;
    }

    int x = (int) (latitude * 1000000);
    int y = (int) (longitude * 1000000);
    userID = getSharedPreferences("user_info", MODE_WORLD_READABLE);

    paraName.add("userId");      paraValue.add(userID.getString("userID", null));
    paraName.add("news_type");   paraValue.add(news_type);
    paraName.add("news_title");  paraValue.add(publish_newstitle.getText().toString());
    paraName.add("news_content");paraValue.add(publish_newscontent.getText().toString());
    paraName.add("x");           paraValue.add(x + "");
    paraName.add("y");           paraValue.add(y + "");

    try {
        File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "myAQ" + File.separator + fileName);

        FileInputStream pfis = new FileInputStream(photoFile);
        ByteArrayOutputStream pbaos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while (pfis.read(buffer) > 0) {
            pbaos.write(buffer);
        }

        String photoData =
                new String(Base64.encode(pbaos.toByteArray(), Base64.DEFAULT));
        pfis.close();

        paraName.add("image");
        paraValue.add(photoData);

        JSONObject jsonObj = new JSONObject();
        for (int i = 0; i < paraName.size(); i++) {
            jsonObj.put(paraName.get(i), paraValue.get(i));
        }
        String jsonString = jsonObj.toString();
        Log.i("test", "upload:" + jsonString);

        // 指定 Post 參數
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("data", jsonString));
        String result = HttpClientTest.doPost(nameValuePairs, Constant.publish_newsURL);

        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        PublishNewsActivity.this.finish();
    } catch (Exception e) {
        Log.i("exception", "submit:" + e.getMessage());
        Toast.makeText(getApplicationContext(), "提交失敗", Toast.LENGTH_SHORT).show();
    }
}

伺服器端收到 data 這個參數後,先解析 JSON,再把 image 欄位 Base64 解碼還原成二進位寫檔,整個往返就完成了。

實務上的幾點補充

Base64 會讓資料膨脹約三分之一。照片稍大就會撞上 HTTP 請求大小限制,正式專案建議改用 multipart/form-data 上傳,或至少先在拍照後做一次縮圖(例如用 BitmapFactory.Options 的 inSampleSize 降採樣)。

網路操作不能跑在主執行緒。範例中的 doPost 在 API 10 之後會直接拋出 NetworkOnMainThreadException,實際使用請包在 AsyncTask、Thread 或 coroutine 裡。

SharedPreferences 的讀取模式。範例中的 MODE_WORLD_READABLE 已不建議使用,新專案請改用 MODE_PRIVATE。

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