简体   繁体   English

拍摄带照相机意图的照片并在imageView或textView中显示?

[英]Take photo w/ camera intent and display in imageView or textView?

I have a question about how to take an image using the camera intent (or camera API) and then bring the image into an imageView for me to display in my application. 我有一个关于如何使用相机意图(或相机API)拍摄图像的问题,然后将图像带入imageView,以便在我的应用程序中显示。 This is what I have so far. 这就是我到目前为止所拥有的。

I setup a button 我设置了一个按钮

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

I setup a Camera method 我设置了一个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);
}

And this is where I am lost. 这就是我迷失的地方。 I am trying to process the image that I took. 我正在尝试处理我拍摄的图像。

    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);
}

My intent is to display the image that you took inside image_view. 我的目的是显示你在image_view中拍摄的图像。 I am not receiving an error, nothing happens. 我没有收到错误,没有任何反应。 When I take the picture, I am asked to either take another picture or after I use the device back button the application force closes. 当我拍照时,我被要求拍摄另一张照片,或者在我使用设备后退按钮后,应用程序强制关闭。 It seems that I am taken out of my application completely, and returning is a big issue. 似乎我完全退出了我的应用程序,返回是一个大问题。 Any suggestions? 有什么建议? What am I missing? 我错过了什么?

O yea, and here is my onActivityResult 是的,这是我的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();
        }

    }
}

I am trying to put the image in getExtras, and then store it to a ByteArray. 我试图将图像放在getExtras中,然后将其存储到ByteArray。 Was another thing I was trying to do. 是我想要做的另一件事。 Not sure how it all comes together. 不知道这一切是如何结合在一起的。

The method which i found to be easy and helpful is this: 我觉得简单有用的方法是这样的:

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);

}

and then in your activity onActivityResult method: 然后在你的活动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 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;
}
}

and then on the ImageView onclick method will be like this: 然后在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);

    }

}

To take photo correctly you should store it in temp file, because data in result intent can be null: 要正确拍照,您应该将其存储在临时文件中,因为结果意图中的数据可以为null:

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);

And then get photo from Uri: 然后从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);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM