Android 照相
在android中,照相功能系統(tǒng)已經(jīng)提供,在app中可以直接使用。當(dāng)手機(jī)從android play里面下載有照相功能的應(yīng)用時(shí), 會(huì)判斷手機(jī)是否支持。不支持,不給予下載。
照相有幾個(gè)步驟:
1. 聲明權(quán)限
2. 使用Camera照相
3. 顯示圖片
1. 聲明權(quán)限
在manifest里面聲明使用Camera:
<uses-feature android:name="android.hardware.camera" />
2. 使用Camera照相
在Activity中,調(diào)用Camera應(yīng)用
private void dispatchTakePictureIntent(int actionCode) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePictureIntent, actionCode); } 3. 顯示圖片
在使用Camera照相成功之后,會(huì)返回回來(lái),要顯示圖片就必須先獲取圖片,然后顯示出來(lái)。
在onActivityResult方法中取得
protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { Bundle extras = intent.getExtras(); Bitmap mImageBitmap = (Bitmap) extras.get("data"); mImageView.setImageBitmap(mImageBitmap); 想要保存圖片到制定目錄,啟動(dòng)Camera應(yīng)用時(shí),需要指定文件
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; }
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; } 感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選