【问题标题】:Taking a Full Size Photo with Camera Intent and Saving It使用相机意图拍摄全尺寸照片并保存
【发布时间】:2015-11-21 11:21:38
【问题描述】:

我正在关注这个 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>

【问题讨论】:

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


    【解决方案1】:

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

    <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 数据 - 它仍然为空,所以我将 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()。它有效。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

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

      实际上,您在应该选择其中之一的地方组合了一些东西。

      The Save the Full-Size Photo section 你是否要么 使用Environment.getExternalStoragePublicDirectory() 使用getExternalFilesDir()。你选择了前者,这很好。但是,您android:maxSdkVersion 添加到&lt;uses-permission&gt; 元素,这是使用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()

      【讨论】:

      • 我的 targetSdkVersion 是 23。我从权限中删除了 android:maxExternalStorage。现在我的 onActivityResult 没有被触发,即使我在其中放置了一些断点并尝试对其进行调试。(选项 2 不起作用)
      • 我也尝试切换到 getExternalFilesDir()。但是,这一次它创建了文件,但是当涉及到 setPic() 步骤时,bmOptions.outWidth 和 bmOptions.outHeight 在解码 mCurrentPhotoPath 后返回 0,这导致在 scaleFactor 步骤中除以零异常。
      • @FigenGüngör:“我从权限中删除了 android:maxExternalStorage”——抱歉,我的意思是 android:maxSdkVersion。 “现在我的 onActivityResult 没有被触发......” - 大概,您没有在运行时请求权限(参见第 2 项)。 “bmOptions.outWidth 和 bmOptions.outHeight 在解码 mCurrentPhotoPath 后返回 0”——也许图像没有存储在那里。文档没有提到许多相机应用程序存在错误,并且可能不一定将图像写入指定位置。
      • @FigenGüngör:他们的代码还有其他错误(mCurrentPhotoPath 既不是路径,也不是有效的Uri,而是相机应用程序可能无法识别并且肯定无法识别的其他内容BitmapFactory)。
      • 哦,我的意思是首先是 android:maxSdkVersion,对此感到抱歉。顺便说一句,我正在测试版本低于 23 的设备上的应用程序,所以我还需要编写那些运行时权限吗?我想我稍后会为 >=23 添加这些权限。
      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 2014-09-04
      • 2017-01-23
      • 2011-05-22
      相关资源
      最近更新 更多