使用相机意图拍照并在imageView或textView中显示?

8

我有一个问题,关于如何使用相机意图(或相机API)拍摄图像,然后将图像带入imageView以供在我的应用程序中显示。这是我目前的代码。

我设置了一个按钮

Button btnPicture = (Button) findViewById(R.id.btn_picture);
    btnPicture.setOnClickListener(this);

我设置了一个Camera方法。
private void Camera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, TAKE_PICTURE_CODE);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, REQUEST_CODE);
}

我在这里遇到了问题,我正在尝试处理我拍摄的图像。

    private void processImage(Intent intent) {
    setContentView(R.layout.imagelayout);
    ImageView imageView = (ImageView)findViewById(R.id.image_view);
    cameraBitmap = (Bitmap)intent.getExtras().get("data");
    imageView.setImageBitmap(cameraBitmap);
}

我的意图是在image_view内显示您拍摄的图像。我没有收到错误信息,也没有发生任何事情。当我拍照时,我被要求再拍一张照片,或者使用设备返回按钮后应用程序强制关闭。似乎我完全离开了我的应用程序,而返回是一个大问题。有什么建议吗?我错过了什么吗?
哦对了,这是我的onActivityResult。
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        if(TAKE_PICTURE_CODE == requestCode) {

        Bundle extras = data.getExtras();
        if (extras.containsKey("data")) {
            Bitmap bmp = (Bitmap) extras.get("data");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] image = baos.toByteArray();
            if (image != null) {
                Log.d(TAG, "image != null");
            }

        } else {
            Toast.makeText(getBaseContext(), "Fail to capture image", Toast.LENGTH_LONG).show();
        }

    }
}

我试图将图片放在getExtras中,然后将其存储到ByteArray中。这是我尝试做的另一件事情。不确定它们如何联系在一起。


1
请发布您的 onActivityResult() 代码。 - Amulya Khare
这是一个很棒的项目,处理了许多复杂性:https://github.com/CameraKit/camerakit-android。不需要使用 onActivityResult(..),并且有简洁的 onRequestPermissionsResult(..) 实现。在这个问题的[100+行]答案的SO海洋中,特别感谢:https://dev59.com/yqHia4cB1Zd3GeqPSFcL#43707269 - Gene Bo
2个回答

15

我发现的一种易于操作且有帮助的方法是:

MainActivity

private static String root = null;
private static String imageFolderPath = null;        
private String imageName = null;
private static Uri fileUri = null;
private static final int CAMERA_IMAGE_REQUEST=1;

public void captureImage(View view) {

    ImageView imageView = (ImageView) findViewById(R.id.capturedImageview);

             // fetching the root directory
     root = Environment.getExternalStorageDirectory().toString()
     + "/Your_Folder";

     // Creating folders for Image
     imageFolderPath = root + "/saved_images";
     File imagesFolder = new File(imageFolderPath);
     imagesFolder.mkdirs();

    // Generating file name
    imageName = "test.png";

    // Creating image here

    File image = new File(imageFolderPath, imageName);

    fileUri = Uri.fromFile(image);

    imageView.setTag(imageFolderPath + File.separator + imageName);

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    startActivityForResult(takePictureIntent,
            CAMERA_IMAGE_REQUEST);

}

然后在您的活动onActivityResult方法中:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {

        switch (requestCode) {
        case CAMERA_IMAGE_REQUEST:

            Bitmap bitmap = null;
            try {
                GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
                bitmap = getImageThumbnail.getThumbnail(fileUri, this);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            // Setting image image icon on the imageview

            ImageView imageView = (ImageView) this
                    .findViewById(R.id.capturedImageview);

            imageView.setImageBitmap(bitmap);

            break;

        default:
            Toast.makeText(this, "Something went wrong...",
                    Toast.LENGTH_SHORT).show();
            break;
        }

    }
}

GetImageThumbnail.java

public class GetImageThumbnail {

private static int getPowerOfTwoForSampleRatio(double ratio) {
    int k = Integer.highestOneBit((int) Math.floor(ratio));
    if (k == 0)
        return 1;
    else
        return k;
}

public Bitmap getThumbnail(Uri uri, Context context)
        throws FileNotFoundException, IOException {
    InputStream input = context.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither = true;// optional
    onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == -1)
            || (onlyBoundsOptions.outHeight == -1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
            : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > 400) ? (originalSize / 350) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither = true;// optional
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional
    input = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    return bitmap;
}
}

那么在ImageView的onclick方法中将会像这样:

public void showFullImage(View view) {
    String path = (String) view.getTag();

    if (path != null) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri imgUri = Uri.parse("file://" + path);
        intent.setDataAndType(imgUri, "image/*");
        startActivity(intent);

    }

}

谢谢,你的示例非常详细,帮了我很多。不过我遇到了强制关闭的问题。当我删除 onlyBoundsOptions.inJustDecodeBounds 这一行时,问题似乎得到了解决,但是事情仍然没有按照我想要的方式工作。我会继续尝试调整。但是你已经帮助我取得了进展,谢谢! - portfoliobuilder
这个可行。考虑将getThumbnail()设为静态方法,您无需使用其所属类的实例即可使用它。 - lemuel

3

为了正确地拍摄照片,您应该将其存储在临时文件中,因为结果意图中的数据可能为空:

final Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
final String pickTitle = activity.getString(R.string.choose_image);
final Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
if (AvailabilityUtils.isExternalStorageReady()) {
    final Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    final Uri fileUri = getCameraTempFileUri(activity, true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
    new Intent[] { takePhotoIntent });
}

activity.startActivityForResult(chooserIntent, REQUEST_CODE);

然后从Uri获取照片:

if (requestCode == ProfileDataView.REQUEST_CODE
                && resultCode == Activity.RESULT_OK) {
            final Uri dataUri = data == null ? getCameraTempFileUri(context,
                false) : data.getData();
                final ParcelFileDescriptor pfd = context.getContentResolver()
                    .openFileDescriptor(imageUri, "r");
                final FileDescriptor fd = pfd.getFileDescriptor();
                final Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fd);
        }

10倍,但您还应该发布getCameraTempFileUri() - WindRider

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接