用相机意图拍摄全尺寸照片并保存

时间:2015-11-21 11:21:39

标签: android image android-camera android-camera-intent

我正在关注此Android开发人员的教程:http://developer.android.com/training/camera/photobasics.html

我使用了本教程中的确切代码。但是,它在createImageFile()函数中创建图像文件时返回null。

请你看看我的代码并告诉我我错过了什么?

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    ImageView mImageView;
    String mCurrentPhotoPath;
    Button takepicturebtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mImageView = (ImageView) findViewById(R.id.imageView);
        takepicturebtn = (Button) findViewById(R.id.takepicturebtn);

        takepicturebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();
            }
        });


    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath ="file:" + image.getAbsolutePath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            setPic();
        }
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private void setPic() {
        // Get the dimensions of the View
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(bitmap);
    }

}

这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.figengungor.takingcamerapicture" >

    <uses-feature android:name="android.hardware.camera"></uses-feature>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"  android:maxSdkVersion="18" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2 个答案:

答案 0 :(得分:2)

我是这个网站上的新手,但我已经遇到了同样的问题。我做了什么: 在Manifest中我使用了这样的代码:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera"></uses-feature>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
<activity android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="portrait">

由于我没有为我的应用程序使用横向方向,因此每次按下按钮时都会从相机中保存图片,新的MainActivity正在创建,而OnCreated方法再次调用。但是创建了前一个文件。 至于Inten数据 - 它仍然是null,所以我把ImageView放在我的文件中(之前更改大小)。我没有使用方法setPic(),而是使用这段代码(不要忘记在课堂上初始化File photoFile):

bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
 imageView = (ImageView) findViewById(R.id.imageView);
 // Resize the bitmap to 150x100 (width x height)
 Bitmap bMapScaled = Bitmap.createScaledBitmap(bitmap, 150, 100, true);
 // Loads the resized Bitmap into an ImageView
 imageView.setImageBitmap(bMapScaled);

或 您可以使用方法setPic(),但需要在此方法mCurrentPhotoPath中的任何位置更改为photoFile.getAbsolutePath()。它有效。

希望它有所帮助。

答案 1 :(得分:0)

  

我使用了本教程中的确切代码

实际上,你把你应该选择的东西组合在一起。

The Save the Full-Size Photo section让你 使用Environment.getExternalStoragePublicDirectory() 使用getExternalFilesDir()。你选择了前者,这很好。但是,您android:maxSdkVersion添加到<uses-permission>元素,这是使用getExternalFilesDir()的说明的一部分。您需要在所有相关Android版本上使用WRITE_EXTERNAL_STORAGE才能使用Environment.getExternalStoragePublicDirectory()

您有三种选择:

  1. 删除android:maxSdkVersion。然后,请确保targetSdkVersion(在app/build.gradle中,假设您有传统的Android Studio项目)为22或更低,或者您在Android 5.1或更低版本上进行测试。

  2. 删除android:maxSdkVersion,同时将targetSdkVersion保留为23(或更高),并在Android 6.0(或更高版本)上进行测试。在这种情况下,您还必须处理WRITE_EXTERNAL_STORAGE在Android 6.0+上具有dangerous权限这一事实,并且需要通过运行时权限系统进行处理。

  3. 切换为使用getExternalFilesDir()代替Environment.getExternalStoragePublicDirectory()