如何在我的Android应用程序中显示刚刚从相机中拍摄的图像?

时间:2014-04-20 01:15:45

标签: android xml photo

我正在尝试使用以下代码拍摄照片并在屏幕上查看:

public class MainActivity extends ActionBarActivity {
    private static final int PICTURE_REQUEST_CODE = 100;
    public Button camera, gallery;
    private Uri fileUri;
    private static File mediaFile;
    ImageView image;
    public String fileName;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera = (Button) findViewById(R.id.button1);
        gallery = (Button) findViewById(R.id.button2);
        createListeners();
    }
    private static Uri getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Mustache");
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");

        return Uri.fromFile(mediaFile);
    }
    public void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFile(); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, PICTURE_REQUEST_CODE);

    }
    public void launchGallery(){
        Intent gallery = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        fileUri = getOutputMediaFile(); // create a file to save the image
        gallery.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(gallery, PICTURE_REQUEST_CODE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
               System.out.println(String.valueOf(requestCode));
               System.out.println(String.valueOf(resultCode));
               System.out.println(data);
               Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
               Uri contentUri = Uri.fromFile(mediaFile);
               mediaScanIntent.setData(contentUri);
               this.sendBroadcast(mediaScanIntent);

    }
    public static final int MEDIA_TYPE_VIDEO = 2;

    private void createListeners() {
        System.out.println("Started CreateListeners for Main Activity");
        camera.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchCamera();
            }

        });

        gallery.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchGallery();
            }
        });
    }


}

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context="com.example.mustache.MainActivity"
    tools:ignore="MergeRootFrame" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:text="@string/main_camera_button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_gravity="bottom"
        android:layout_weight="1"
        android:text="@string/main_gallery_button" />

</LinearLayout>

然而,应用程序拍摄照片并将其保存到我的图库,但随后返回主屏幕而不做任何事情。如何让它显示照片?

5 个答案:

答案 0 :(得分:4)

唯一的问题是您没有显示捕获的图像。

您需要在ImageView中添加Layout并在onActivityResult

中设置捕获的图片

像这样更改onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri contentUri = Uri.fromFile(mediaFile);

    ImageView imageView = (ImageView)findViewById(R.id.imageView1);
    imageView.setImageURI(contentUri);
}

另外,在布局中添加ImageView

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_weight="1"/>

答案 1 :(得分:1)

除了一件事,一切看起来都很好:你刚刚创建了ImageView对象但没有引用。您应该对代码进行一些更改,如下所示:

将ImageView添加到xml布局文件中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context="com.example.mustache.MainActivity"
    tools:ignore="MergeRootFrame" >

  <Button .... />
   <Button .... />
  <ImageView
        android:id="@+id/imageview"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
   </LinearLayout>

然后引用您的Activity类:

public class MainActivity extends ActionBarActivity 
    {
        private static final int PICTURE_REQUEST_CODE = 100;
        public Button camera, gallery;
        ImageView image;
       .........
       ........
        protected void onCreate(Bundle savedInstanceState) {
            System.out.println("Started Main Activity");
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           image = (ImageView)findViewById(R.id.imageview);
         }

然后到 onActivityResult

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
               super.onActivityResult(requestCode, resultCode, data);
                   System.out.println(String.valueOf(requestCode));
                   System.out.println(String.valueOf(resultCode));
                   System.out.println(data);
              if(resulCode == RESULT_OK && requestCode == PICTURE_REQUEST_CODE)
            {
                   Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                   Uri contentUri = Uri.fromFile(mediaFile); 

                    image.setImageUri(contentUri);//set uri of captured image to imageview
                   mediaScanIntent.setData(contentUri);
                   this.sendBroadcast(mediaScanIntent);

            }

        }

确保为启动相机和从图库中选择图像设置不同的RequestCode。

答案 2 :(得分:1)

您需要Imageview

public class MainActivity extends ActionBarActivity {
    private static final int PICTURE_REQUEST_CODE = 100;
    public Button camera, gallery;
    private Uri fileUri;
    private static File mediaFile;
    ImageView image;
    public String fileName;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        camera = (Button) findViewById(R.id.button1);
        gallery = (Button) findViewById(R.id.button2);
        createListeners();
    }
    private static Uri getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Mustache");
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");

        return Uri.fromFile(mediaFile);
    }
    public void launchCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFile(); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, PICTURE_REQUEST_CODE);

    }
    public void launchGallery(){
        Intent gallery = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        fileUri = getOutputMediaFile(); // create a file to save the image
        gallery.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(gallery, PICTURE_REQUEST_CODE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
               System.out.println(String.valueOf(requestCode));
               System.out.println(String.valueOf(resultCode));
               System.out.println(data);
               Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
               Uri contentUri = Uri.fromFile(mediaFile);
               mediaScanIntent.setData(contentUri);
               this.sendBroadcast(mediaScanIntent);

    }
    public static final int MEDIA_TYPE_VIDEO = 2;

    private void createListeners() {
        System.out.println("Started CreateListeners for Main Activity");
        camera.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchCamera();
            }

        });

        gallery.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                launchGallery();
            }
        });
    }


}

答案 3 :(得分:0)

这是一种简单的技术。您应该使用AlertDialog.Builder来显示3个选项,如:

1)从相机拍摄照片 2)从画廊中选择 3)取消

然后按照以下步骤进行操作

请参阅以下代码以获取帮助......

    ImageView profile_img; //When you select image either from Gallery or take from Camera the code will set your selected image to this ImageView... 

    Context context;

    final CharSequence[] items = { "Take Picture from camera", "Choose from gallery", "Cancel" };

    private static final int REQUEST_CAMERA = 0;

    private static final int SELECT_IMAGE = 1;

    Bitmap bmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.your_xml_layout_name);

        context = YourActivityClass.this;

        profile_img = (ImageView) findViewById(R.id.profile_img);

        profile_img.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) 
    {
        int id = v.getId();

        switch (id) 
        {

        case R.id.profile_img:

            selectImage();

            break;
        }
    }

    private void selectImage()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);

        alert.setTitle("Choose Options...");

        alert.setItems(items, new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dialog, int position) 
            {
                if(items[position].equals("Take Picture from camera"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(intent, REQUEST_CAMERA);
                }
                else if(items[position].equals("Choose from gallery"))
                {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(intent, SELECT_IMAGE);
                }
                else if(items[position].equals("Cancel"))
                {
                    dialog.dismiss();
                }
            }
        });

        alert.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK)
        {
            if(requestCode == REQUEST_CAMERA)
            {               
                Uri uri = (Uri) data.getData();

                try 
                {
                    bmp = decodeUri(uri);

                    profile_img.setImageBitmap(bmp);
                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                }
            }
            else if(requestCode == SELECT_IMAGE)
            {
                Uri uri = data.getData();

                try 
                {
                    bmp = decodeUri(uri);

                    profile_img.setImageBitmap(bmp);
                } 
                catch (FileNotFoundException e) 
                {
                    e.printStackTrace();
                }


            }
        }
    }

    public String getPath(Uri uri) 
    {
        String[] projection = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException 
    {
        BitmapFactory.Options o = new BitmapFactory.Options();

        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 70;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;

        int scale = 1;

        while (true) 
        {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) 
            {
                break;
            }
            width_tmp /= 2;

            height_tmp /= 2;

            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();

        o2.inSampleSize = scale;

        return BitmapFactory.decodeStream(
                getContentResolver().openInputStream(selectedImage), null, o2);
    }

希望这会对你有所帮助......祝你好运

答案 4 :(得分:0)

// try this way,hope this will help you...

**XML** code

**activity_main**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:layout_weight="1">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_launcher"/>
    </LinearLayout>
    <Button
        android:id="@+id/btnCamera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Camera" />

    <Button
        android:id="@+id/btnGallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Gallery" />

</LinearLayout>

**ACTIVITY** code

**MainActivity**
public class MainActivity extends Activity {

    final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;

    private Button btnCamera;
    private Button btnGallery;
    private ImageView imageView;
    private String imgPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("Started Main Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCamera = (Button) findViewById(R.id.btnCamera);
        btnGallery = (Button) findViewById(R.id.btnGallery);
        imageView = (ImageView) findViewById(R.id.imageView);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            }
        });

        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
            }
        });
    }

    public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }

    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = managedQuery(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);

            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAPTURE_IMAGE) {
                imageView.setImageBitmap(BitmapFactory.decodeFile(getImagePath()));
            } else if (requestCode == PICK_IMAGE) {
                imageView.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
            }
        }

    }

}

Note : add this permission on you "AndroidManifest.xml"
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />