今回は Taking Photos Simply です。
前回はオーディオの操作でしたが
今回はカメラ操作のお話です。
まず、もうお決まりごとになってきましたが
マニフェストファイルにカメラ使用の記述をします。
<manifest ... >
<uses-feature android:name="android.hardware.camera" />
...
</manifest ... >
当たり前の事ですが、
カメラを使用しないなら、この記述は削除するべきです。
次にカメラアプリの起動です。
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
戻ってきたインテントから取られた写真のデータが見れます。
写真がうまく取れてるかのチェックもしときます。
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
写した写真を見る方法
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
インテントから画像データを取得して表示
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
写真の保存の為のファイルパスを用意
APIレベル8以降の場合
storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getAlbumName()
);
APIレベル8未満の場合
storageDir = new File (
Environment.getExternalStorageDirectory()
+ PICTURES_DIR
+ getAlbumName()
);
ファイル名の作成
名前の重複を回避します。
private File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File image = File.createTempFile(
imageFileName,
JPEG_FILE_SUFFIX,
getAlbumDir()
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
作成したファイル名はインテントに渡しておきましょう。
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
そしてさらに、Android Galleryアプリケーションで、
他のアプリが利用できるようにシステムのメディアスキャナーへ
ファイル名をブロードキャストします。
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
最後に、大きすぎる画像を画面に収まるようにスケーリングする方法。
private void setPic() {
表示の大きさ
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
ビットマップの大きさ
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
縮小率
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
スケーリングして再表示
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
}
本日は以上です。