/** * 打开系统像机的功能 * @param view */ public void startCamera(View view){ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(intent); }
这里是通过 调用一个意图开打开的
当我们自己的应用程序在清单文件中添加
<intent-filter> <action android:name="android.media.action.IMAGE_CAPTURE" /> <category android:name="android.intent.category.DEFAULT" > </category> </intent-filter>
/** * 打开系统像机的功能 * @param view */ public void startCamera(View view){ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 1234); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent arg2) { super.onActivityResult(requestCode, resultCode, arg2); if (resultCode== RESULT_OK) { if (resultCode == 1234) { Bundle bundle = arg2.getExtras(); Bitmap bitmap = (Bitmap) bundle.get("data"); } } }
当然要注意到的是 这里获取到的只是照片的缩略图
这里需要设置一个自定义的存储路径,然后从固定的路径中获取我们所拍摄的照片
拍摄前的设置
//设置自定义存储路径 mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/systemCemer"; //存储文件夹操作 File outFilePath = new File(mFilePath); if (!outFilePath.exists()) { outFilePath.mkdirs(); } //设置自定义照片的名字 String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); mFilePath = mFilePath + "/" + fileName + ".jpg"; File outFile = new File(mFilePath); Uri uri = Uri.fromFile(outFile); //拍照 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, 305);
在Activity中
protected void onActivityResult(int requestCode, int resultCode, Intent data) { }
if (resultCode==RESULT_OK){ if (requestCode==305){ if (data!=null){ }else { if (BuildConfig.DEBUG) Log.d("SystemCemerActivity", mFilePath); final Bitmap bitmap = loadingImageBitmap(mFilePath); if (bitmap!=null){ mImageView.setImageBitmap(bitmap); } } } }
这里面依据image 的path来获取了一个bitmap对象,然后将其设置给imageview来显示,使用到的loadingImageBitmap方法是用来加载高清大图的适当缩放功能的方法
public Bitmap loadingImageBitmap(String imagePath) { /** * 获取屏幕的宽与高 */ final int width = getWindowManager().getDefaultDisplay().getWidth(); final int height = getWindowManager().getDefaultDisplay().getHeight(); /** * 通过设置optios来只加载大图的尺寸 */ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeFile(imagePath, options); /** * 计算手机宽高与显示大图的宽高,然后确定缩放有比例 */ int widthRaio = (int) Math.ceil(options.outWidth/(float)width); int heightRaio = (int) Math.ceil(options.outHeight/(float)height); if (widthRaio>1&&heightRaio>1){ if (widthRaio>heightRaio){ options.inSampleSize = widthRaio; }else { options.inSampleSize = heightRaio; } } /** * 设置加载缩放后的图片 */ options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(imagePath, options); } catch (Exception e) { e.printStackTrace(); } return bitmap; }