【问题标题】:Camera does not set Image on ImageView相机未在 ImageView 上设置图像
【发布时间】:2015-11-30 05:23:31
【问题描述】:

当我尝试将图像从相机设置为图像视图时,ImageView 返回空白。我已在清单和所有内容中授予权限。它仍然不起作用。自上周以来,我一直坚持这一点。请帮忙。代码如下:

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity
{
    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_TAKE_PHOTO = 1;
    String mCurrentPhotoPath;
    ImageView mImageView;


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

        Button button = (Button) findViewById(R.id.button);
        mImageView = (ImageView) findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                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();
            Log.d("","file place:"+mCurrentPhotoPath);
            return image;
        }
    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_TAKE_PHOTO);
            }
        }
    }

    public static Bitmap decodeSampledBitmapFromFile(String path,
                                                     int reqWidth, int reqHeight) { // BEST QUALITY MATCH

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        }

        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }


        options.inSampleSize = inSampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //setPic();
        File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
        mImageView = (ImageView) findViewById(R.id.imageView);
        mImageView.setImageBitmap(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250));
    }
}

Logcat:

11-30 11:30:12.479 11680-11680/com.example.samarth.cameraimagecapture E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity {com.example.samarth.cameraimagecapture/com.example.samarth.cameraimagecapture.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.samarth.cameraimagecapture/com.example.samarth.cameraimagecapture.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2458)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2486)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2000)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.samarth.cameraimagecapture/com.example.samarth.cameraimagecapture.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:2997)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2445)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2486) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2000) 
at android.app.ActivityThread.access$600(ActivityThread.java:128) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4517) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
at com.example.samarth.cameraimagecapture.MainActivity.onActivityResult(MainActivity.java:175)
at android.app.Activity.dispatchActivityResult(Activity.java:4654)
at android.app.ActivityThread.deliverResults(ActivityThread.java:2993)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2445) 
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2486) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2000) 
at android.app.ActivityThread.access$600(ActivityThread.java:128) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4517) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760) 
at dalvik.system.NativeStart.main(Native Method) 

【问题讨论】:

  • 我认为您从 onActivityResult 中获取了错误的图像,并且您创建的 imageFile 不同
  • @sam24 您是否在AndroidManifest.xml 文件中添加了&lt;uses-permission android:name="android.permission.CAMERA" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; 这些权限?

标签: android android-logcat android-camera-intent


【解决方案1】:
String imageFileName,imagePath;

private void clickPhotoFromCamera() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            imageFileName = "JPEG_" + timeStamp + ".jpg";
            File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName);
            uri = Uri.fromFile(imageStorageDir);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 1);

        }

    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                    imagePath = uri.getPath();
                    Bitmap myBitmap = BitmapFactory.decodeFile(imagePath.getAbsolutePath());
                    imageView.setImageBitmap(myBitmap);
                }
            }
        }

【讨论】:

    【解决方案2】:

    这就是问题所在。当您发送获取图片的意图时,您提供了一个 Uri 来将图片写入其中。

    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
    

    然而,在onActivityResult 方法中,您正在创建一个全新的文件(将为空)并将 ImageView 对象设置为从该文件中提取的位图。

    以下是解决此问题的方法。

    1) 使用你传递给意图的文件

    // Make this a class variable
    File photoFile;
    
    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
                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_TAKE_PHOTO);
                }
            }
        }
    

    然后在onActivityResult方法中:

    mImageView = (ImageView) findViewById(R.id.imageView);
    mImageView.setImageBitmap(decodeSampledBitmapFromFile(photoFile.getAbsolutePath(), 500, 250));
    

    除了保存文件,您还可以只保存文件路径并在onActivityResult中重新初始化文件

    2) 或者,如果您只想将结果设置为 imageView,我建议:

    删除这一行

    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
    

    onActivityResult:

    if (result == Activity.RESULT_OK && data != null && data.getData() != null) {
        mImageView = (ImageView) findViewById(R.id.imageView);
        // data.getData() will return the bitmap
        mImageView.setImageBitmap(data.getData());
    }
    

    请注意,在进行其他操作之前,您真的应该检查(requestCode == TAKE_PHOTO_REQUEST),因为您想确保它是对您拍照请求的回应

    【讨论】:

    • 我收到此错误:原因:java.lang.RuntimeException:将结果 ResultInfo{who=null, request=1, result=-1, data=null} 传递给活动 {com.example .samarth.cameraimagecapture/com.example.samarth.cameraimagecapture.M‌​ainActivity}: java.lang.NullPointerException
    【解决方案3】:

    尝试将您的代码更改为

    onActivityResult

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //setPic();
      if(resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PHOTO){
        Log.d("onActivityResult","file place:"+mCurrentPhotoPath);
        mImageView.setImageBitmap(decodeSampledBitmapFromFile(mCurrentPhotoPath, 500, 250));
      }
    }
    

    创建图像文件

    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 = image.getAbsolutePath();
            Log.d("","file place:"+mCurrentPhotoPath);
            return image;
        }
    

    【讨论】:

    • 我收到此错误:原因:java.lang.RuntimeException:将结果 ResultInfo{who=null, request=1, result=-1, data=null} 传递给活动 {com.example .samarth.cameraimagecapture/com.example.samarth.cameraimagecapture.MainActivity}:java.lang.NullPointerException
    • 我仍然收到此错误。我能做些什么来纠正它?
    • 如果错误仍然存​​在,您可以发布您的 logcat 吗?
    • 请检查编辑
    • 我已经更新了代码.. 但是你能告诉我你使用哪个安卓操作系统来运行应用程序吗?
    猜你喜欢
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多