Android 調用系統拍照 筆記

    因爲臨時須要作個簡單的Android程序,其中涉及調用系統拍照並保存照片。以前沒有任何Java和Android經驗,coding中遇到很多問題,特記錄以供參考。java

    Google一下能找到很多現成的調用系統拍照的代碼,可弄了一天也沒成功。測試手機爲Defy,系統是Android4.0/MIUI-1.11-9。先附上網上搜所的代碼,後說明遇到的問題:android

    1.響應按鈕點擊事件,調用系統拍照,其中RESULT_CAPTURE_IMAGE爲自定義拍照標誌。ide

public void onClick(View v) {
    startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE,RESULT_CAPTURE_IMAGE);
}

     2.Override onActivityResult(int requestCode, int resultCode, Intent data)方法,在此方法中保存圖片。其中imagePath在此類中已定義,操做sdcard權限在清單文件中已添加,判斷sdcard是否存在以及指定文件目錄是否存在在此以前都已作處理。測試

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == RESULT_CAPTURE_IMAGE) {
        if(resultCode == RESULT_OK) {
            File file = new File(imagePath);
            Bitmap bitmap = (Bitmap)data.getExtras().get("data");
            try {
                BufferOutputStream bos = new BufferOutputStream(new FileOutputStream(file));
                //採用壓縮轉檔方法
                bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos);
                bos.flush();
                bos.close();
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

    用以上代碼碰到的問題:this

  1. 在MIUI下沒法取到照片數據,跟蹤發現data.getExtras()爲空,以後使用BitmapFactory.decodeFile()方法解決;    
  2. 手機上測試沒有保存圖片,跟蹤發現data爲null,繼續Google,找到如下代碼

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(new File(imagePath));
intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(intent,RESULT_CAPTURE_IMAGE);

    將按鈕onClick方法中採用以上代碼,調用系統拍照並肯定以後,沒法返回程序Activity。繼續Google,終於找到解決辦法,代碼以下(在 if(resultCode == RESULT_OK)裏面)

Bitmap bitmap = null;
File file = new File(imagePath);
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
if(bitmap == null) {
     Toast.makeText(this,R.string.image_save_error,Toast.LENGTH_LONG).show();
}
try {
    BufferOutputStream bos = new BufferOutputStream(new FileOutputStream(file));
    bitmap.compress(Bitmap.CompressFormat.JPEG,80,bos);
    bos.flush();
    bos.close();
}catch(FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e) {
    e.printStackTrace();
}
super.onActivityResult(requestCode,resultCode,data);

   從新編譯後, 在機器上測試經過。其中主要參考連接爲 android調用系統相機拍照 獲取緣由 以及 android調用系統相機實現拍照功能;其中獲取緣由一文中的代碼spa

Uri u = 
 Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), 
   f.getAbsolutePath(), null, null));

進過跟蹤發現圖片路徑解析錯誤,最後直接使用了.net

bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

來獲取bitmap值。

    第一次寫android程序,對整個開發環境,開發語言以及Android API很不熟悉,花費了很多時間。以上文字感受很是凌亂,代碼也只在一款機器上通過測試,但願能給本身和別人有所幫助。code

相關文章
相關標籤/搜索