自己開發的應用程式中如何調用Camera來照相儲存圖片

來源:互聯網
上載者:User

我開發的應用程式用到了SDCard來儲存Camera所拍攝的照片。

 Manifest 檔案中需要配置的許可權和特徵(feature)如下:

 (1)<uses-permission android:name="android.permission.CAMERA" />
// 程式具有訪問手持功能照相機的許可權

(2)<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />//程式具有訪問外部儲存空間(SDCard)的許可權

(3)<uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

上面這個屬性就是手持功能必須具有照相機功能。這個屬性就是Google Play用來過濾手持功能的,如果裝置沒有網路攝影機,這個APP就不會顯示,你也就不能安裝這個

應用程式。

應用程式的大致代碼如下:

變數定義如下:

// get picture from camera
  private static final int PHOTO_WITH_CAMERA = 1010;

  // picture file
  private File pictureFile;

當觸發一個事件(比如說點擊一個按鈕時,開啟Camera),代碼如下:

String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED)) {
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

      //MediaStore.ACTION_IMAGE_CAPTURE 調用Camera 得到一個圖片並返回這個圖片
      pictureFile = new File(PHOTO_DIR, getPhotoFileName());//getPhotoFileName() 產生的圖片名稱

      try {
        pictureFile.createNewFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureFile));//將圖片儲存,名稱為上面產生的圖片名稱
      }
      catch (IOException e) {
        e.printStackTrace();
      }

      startActivityForResult(intent, PHOTO_WITH_CAMERA);
    }

 //According to current time to generate the name of the picture file

 private String getPhotoFileName() {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
    return dateFormat.format(date) + ".jpg";
  }

這種解決方案有個小小問題,就是點擊自己應用程式按鈕時候的時間(檔案名稱根據它產生),開啟照相機後可能過一段時間再照相(這時候才儲存圖片,名稱是前面提到的)。

上面的文字,紅色字型部分為注釋。

希望對您有所協助,共同學習吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.