public class MainActivity extends Activity {
ImageView captruepic;
int requestCode = 0;
String path = "/mnt/sdcard/pic.jpg";
int height = 0;
int width = 0;
File file = new File(path);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captruepic = (ImageView) findViewById(R.id.captruepic);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, requestCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == this.requestCode && resultCode == RESULT_OK) {
// Bundle bundle = data.getExtras();
// (Bitmap)bundle.get("data");
Bitmap bit = null;
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true; 表示只返回照片的尺寸值 不解码照片本身
options.inJustDecodeBounds = true;
bit = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
// 这时候options.outHeight options.outWidth 记录的就是照片的尺寸
height = options.outHeight;
width = options.outWidth;
Display display = this.getWindowManager().getDefaultDisplay();
if (options.outHeight > 0 && options.outWidth > 0) {
// 一般手机拍照的照片的尺寸都比手机屏幕的尺寸大 所以这边用照片的高 宽 除以 屏幕的高 宽
int Height = options.outHeight / display.getHeight();
int Width = options.outWidth / display.getWidth();
// inSampleSize If set to a value > 1, requests the decoder
// to subsample the original image, returning a smaller
// image to save memory 简单的说就是inSampleSize > 1
// 时候返回的照片是原照片的1/inSampleSize倍
options.inSampleSize = Height > Width ? Height : Width;
}
// options.inJustDecodeBounds = false; 表示解码照片本身
options.inJustDecodeBounds = false;
bit = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
captruepic.setImageBitmap(bit);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 开启Camera
如果直接执行startActivityForResult(intent, requestCode);那么在 onActivityResult(int requestCode, int resultCode, Intent data)中的data参数会返回拍的照片
使用Bundle bundle = data.getExtras();
Bitmap bit = (Bitmap)bundle.get("data");获得
如果使用Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 开启Camera
然后设置了intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));照片保存的文件的Uri 那么在 onActivityResult(int requestCode, int resultCode, Intent data)中的data参数不会返回拍的照片,要想获得照片可以通过 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
补充说明:
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
这句话中的MediaStore.EXTRA_OUTPUT是为了告诉android设备不要将返回的图片压缩成很小的尺寸,而且它将告诉应用程序,你想将图片保存在哪个位置。