android 照相
在android中,照相功能系統已經提供,在app中可以直接使用。當手機從android play裡面下載有照相功能的應用時, 會判斷手機是否支持。不支持,不給予下載。
照相有幾個步驟:
1. 聲明權限
2. 使用Camera照相
3. 顯示圖片
1. 聲明權限
在manifest裡面聲明使用Camera:
[html]
<uses-feature android:name="android.hardware.camera" />
2. 使用Camera照相
在Activity中,調用Camera應用
[java]
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
3. 顯示圖片
在使用Camera照相成功之後,會返回回來,要顯示圖片就必須先獲取圖片,然後顯示出來。
在onActivityResult方法中取得
[java]
<pre name="code" class="java">@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
Bundle extras = intent.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}</pre>
<pre></pre>
<pre></pre>
想要保存圖片到制定目錄,啟動Camera應用時,需要指定文件
[java]
[java]
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try {
f = setUpPhotoFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
}
[java]
[java]
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_"+ timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, "jpg", albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}