Android系列之调用系统相机

在这次的开发中使用到了调用相机的功能,记录如下:

调用系统相机,获取照片方法如下:


File outputImage = new File(filename); //需要具体的文件名称和路径

Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(outputImage);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

以上的代码虽然可以获取照片,但是却也什么都做不了,因为,我们可能需要对这些照片进行额外的操作,比如放到特定的文件夹,或者缩放,
或者裁剪。

将照片放到特定的位置

如果只是调用 Environment.getExternalStorageState() ,这会将照片直接保存在 SD 卡的根目录,下面的代码可以将照片保存到 SD
卡的任意地方,如果目录不存在,就会创建一个新的目录:

    private File createOutputFile(String path, String fileName) {

        String storageStatus = Environment.getExternalStorageState();

        if(Environment.MEDIA_REMOVED.equals(storageStatus)) {
            Log.i(TAG, "SD 卡不存在");
            return null;
        }

        File pictureDir = new File(Environment.getExternalStorageDirectory(), path);


        if(! pictureDir.exists()) {

            if(! pictureDir.mkdirs()) {
                Log.i(TAG, "目录创建失败");
            }
        }

        File file = new File(pictureDir, fileName);

        return file;
    }

对照片进行裁剪

以下的代码可以启动一个裁剪器,对刚刚拍好的照片利用系统相机的功能进行裁剪:

 Intent intent = new Intent("com.android.camera.action.CROP");
 intent.setDataAndType(imageUri, "image/*");
 intent.putExtra("aspectX", 1);
 intent.putExtra("aspectY", 1);
 intent.putExtra("outputX", 200);
 intent.putExtra("outputY", 200);
 intent.putExtra("scale", true);
 intent.putExtra("return-data", false);
 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
 intent.putExtra("noFaceDetection", true);

©2024 Rayjun    PowerBy Hexo