How to use a clicked picture in a new activity?

2019-01-20 05:34发布

问题:

I want to use android phone camera to click a picture and then use it in another activity. I could not find any exact method, so I tried to get path of the picture where it is saved and then use it in the other activity.

private OnClickListener cameraBclicked = new OnClickListener() {
    public void onClick(View v) {

        Intent m_Intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(m_Intent, TAKE_PICTURE);
    }
};

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data){

    if ( requestCode == TAKE_PICTURE)
    {
        Uri selectedImage = data.getData();
        Intent intent1 = new Intent(picsource.this,NewScreen.class);
        intent1.putExtra("path", selectedImage);
        startActivity(intent1);
    }

Now, the problem is that the uri comes out to be null.. please correct the above code..

回答1:

To start the camera activity you can use follow code

Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
startActivityForResult(cameraIntent, CAMERA_REQUEST); 

After captiring image you will get captured image in the bitmap format in onActivityResult method. Now when you get the bitmap write the bitmap in the external storage and the pass the path of the image to anothe activity where you want to pass. From second activity you can open the file and get the image.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
   if (requestCode == 1) {  
        Bitmap bmp = intent.getExtras().get("data");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

         bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
         byte[] byteArray = stream.toByteArray(); // convert camera photo to byte array

         // save it in your external storage.
        FileOutputStream fo = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/_camera.png"));

        fo.write(byteArray);
        fo.flush();
        fo.close();
   }  
} 


回答2:

I already had this problem, Here's my code bug

Bitmap photo = (Bitmap) data.getData();// This code return null

My problem was resolved by modifying the code

Bitmap photo = (Bitmap) data.getExtras().get("data");