首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >挑选一张照片或拍摄一张照片,并使用onActivityResult()来处理两者都不起作用的情况

挑选一张照片或拍摄一张照片,并使用onActivityResult()来处理两者都不起作用的情况
EN

Stack Overflow用户
提问于 2015-07-10 17:49:11
回答 2查看 1.7K关注 0票数 0

我正在尝试创建一个应用程序,因为我既可以拍摄新照片,也可以使用现有的照片。我让这两个函数单独工作,但不能一起工作。当Uri imageUri = data.getData();运行时,应用程序崩溃。

代码如下:

代码语言:javascript
复制
 public void btnPhotoClicked(View v) {

    //Use to invoke a Camera
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //Create a variable with the filepath generated by the android operating system, Like a baws

    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    if (pictureDirectory.exists()) {
        File test1 = new File(pictureDirectory, "100MEDIA/");
        if (test1.exists()) {
            pictureDirectory = test1;
        } else {
            File test2 = new File(pictureDirectory, "100ANDRO/");
            if (test2.exists()) {
                pictureDirectory = test2;
            } else {
                File test3 = new File(pictureDirectory, "Camera/");
                if (!test3.exists()) {
                    test3.mkdirs();
                }
                pictureDirectory = test3;
            }
        }
    } else {
        pictureDirectory = new File(pictureDirectory, "Camera/");
        pictureDirectory.mkdirs();
    }

    String pictureName = getPictureName();
    File imageFile = new File(pictureDirectory, pictureName);
    Uri pictureUri = Uri.fromFile(imageFile);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);


    //Start intent and anticipate result
    startActivityForResult(cameraIntent, CAMERA_RESULT);
}

下面是protected void onActivityResult(int requestCode, int resultCode, Intent data)的代码

代码语言:javascript
复制
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {
    //if we are here everything processed successfully

    if (requestCode==IMAGE_GALLERY_REQUEST) {
        //If we are here we came from the Välj existerande build
        Log.d("MainActivity", data.toString());
        Toast.makeText(this, "IMAGE GALLERY_REQUEST", Toast.LENGTH_LONG).show();
        //the address of the image on the device SD-card
        Uri imageUri = data.getData();

        //Declare a stream to read the image data from the SD-card
        InputStream inputStream;

        //Getting a Input stream based upon the image uri
        try {
            //if it execute flawlessly
            inputStream = getContentResolver().openInputStream(imageUri);

            Bitmap image = BitmapFactory.decodeStream(inputStream);

            //show the image to the user

            mImageView.setImageBitmap(image);

        } catch (FileNotFoundException e) {
            //show massage saying if the image is unavailable
            Toast.makeText(this, "Could not open image", Toast.LENGTH_LONG).show();
        }

    } else if (requestCode == CAMERA_RESULT) {
        //We are here because we have received a result from the camera
        Toast.makeText(this, "CAMERA RESULT", Toast.LENGTH_LONG).show();
        Log.d("MainActivity", data.toString());
        //the address of the image on the device SD-card
        Uri imageUri = data.getData();

        //Declare a stream to read the image data from the SD-card
        InputStream inputStream;

        //Getting a Input stream based upon the image uri
        try {
            //if it execute flawlessly
            inputStream = getContentResolver().openInputStream(imageUri);

            Bitmap image = BitmapFactory.decodeStream(inputStream);
            //show the image to the user

            mImageView.setImageBitmap(image);

        } catch (FileNotFoundException e) {
            //show massage saying if the image is unavailable
            Toast.makeText(this, "Could not open image", Toast.LENGTH_LONG).show();
        }



    }

}
EN

回答 2

Stack Overflow用户

发布于 2015-07-10 19:12:47

尝试使用此选项代替图像uri

代码语言:javascript
复制
if (resultCode == RESULT_OK)
        {
            if (requestCode == 1) 
            {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) 
                {
                  if (temp.getName().equals(tempFile)) 
                  {
                        f = temp;
                        //File photo = new File(Environment.getExternalStorageDirectory(), tempFile);
                        break;
                    }
                }
                try
                {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions); 
                    final int THUMBNAIL_SIZE = 100;
                    bitmap = Bitmap.createScaledBitmap(bitmap,THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);

                    img.setImageBitmap(bitmap);

                    String path = android.os.Environment.getExternalStorageDirectory()+ File.separator;

                    File file = new File(path,tempFile);

                    updPath=file.toString();
                    imgSel = true;
                    success=true;
                }
                catch (Exception e) 
                {
                    Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
                }
            } 
            else if (requestCode == 2) 
            {
                try
                {
                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaColumns.DATA };
                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    File outputPath= new File(android.os.Environment.getExternalStorageDirectory(), tempFile);
                    updPath = outputPath.toString();
                    copyFile(picturePath, updPath);

                    Bitmap thumbnail = (BitmapFactory.decodeFile(updPath));
                    final int THUMBNAIL_SIZE = 100;
                    thumbnail = Bitmap.createScaledBitmap(thumbnail,THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
                    ByteArrayOutputStream bytearroutstream = new ByteArrayOutputStream(); 
                    thumbnail.compress(Bitmap.CompressFormat.JPEG, 100,bytearroutstream);
                    img.setImageBitmap(thumbnail);
                    imgSel = true;
                    success=true;
                }
                catch (Exception e) 
                {
                    Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }
票数 0
EN

Stack Overflow用户

发布于 2015-07-10 19:35:07

默认的Android相机应用程序仅在返回的Intent中传回缩略图时才返回非空intent。如果您传递带有要写入的URI的EXTRA_OUTPUT,它将返回一个null意图,图片位于您传入的URI中。

你可以通过查看GitHub上相机应用的源代码来验证这一点:

你的应用程序就会崩溃。因为getContentResolver().openInputStream(imageUri)调用空对象的方法。imageUri为空。

来自documentation

公共静态最终字符串EXTRA_OUTPUT

在API级别3中添加

Intent-extra的名称,用于指示要用于存储请求的图像或视频的内容解析器Uri。

常量值:"output“

所以,你调用ACTION_IMAGE_CAPTURE intent,你应该像这样传递额外的:

代码语言:javascript
复制
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri  = Uri.parse("file:///sdcard/photo.jpg");
photo.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takePicture,requestCode);

然后在onActivityResult中

代码语言:javascript
复制
if (requestCode == CAMERA_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            File file = new File(Environment.getExternalStorageDirectory().getPath(), "photo.jpg");
            Uri uri = Uri.fromFile(file);
            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                bitmap = crupAndScale(bitmap, 300); // if you mind scaling
                pofileImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

已更新

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31337724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档