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

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>

但是,该应用程序拍摄了一张照片并将其保存到我的画廊,但随后不做任何操作就返回主屏幕。 如何使其显示照片?

===============>>#1 票数:4 已采纳

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

您需要在Layout添加ImageView并在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"/>

===============>>#2 票数: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。

===============>>#3 票数: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();
            }
        });
    }


}

===============>>#4 票数: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);
    }

希望这对您有帮助...祝您好运

===============>>#5 票数: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" />

  ask by A.J. Uppal translate from so

未解决问题?本站智能推荐:

1回复

如何为Android创建宝丽来效果?

我试图弄清楚如何在正在创建的应用程序中为照片创建拍立得效果。.我到处都看不到,无法弄清楚从哪里开始。 我需要这样的东西:
1回复

如何在应用程序中编辑通过相机拍摄的照片?

在我的应用程序中,我使用相机拍照。 我使用以下代码启动摄像头活动: 这段代码有效,但是如何在我的主Activity在onActivityResult()获取数据之前编辑预览图像(裁剪,旋转等onActivityResult() ? 或者如何从应用程序中为图像启动照片编辑器?
1回复

获取图像Uri +在Android中用相机拍摄的照片的缩略图

我想用我使用内置Android相机制作的图片更新ImageView。 我使用以下代码: 之后我获得了这张照片: 但是使用这个代码,无论我做什么,我只得到我制作的照片的缩略图 - 我的问题是我如何才能获得刚拍摄的照片的Uri,以便不使用缩略图而是使用原始图像? PS。 我
1回复

在Android应用中拍摄并发送照片

我目前正试图从我的应用程序中拍摄并发送照片。 我用不同的方式搞砸了,但我要么在拍摄照片之前得到关于如何发送电子邮件的选项,要么根本没有。 我需要发送图片然后选择消息传递客户端。 有帮助吗?
1回复

如何在运行Android OS的手机上检索相机拍摄的照片?

我正在开发一个Android应用程序,该应用程序可以检索手机摄像头拍摄的照片并将其转换为其他格式。 如何获取刚刚拍摄的照片以及一段时间前拍摄但仍存在于手机中的照片?
2回复

使用Silverlight(混合)显示文件夹中的图像

我有一个网络目录,其中包含我们公司所有员工照片的转储。 这些图像被命名为FirstnameLastinitial.jpg 。 我最终试图在Silverlight中构建这些图片的照片浏览器,但我想我将从如何从该位置收获图片开始。 我想我应该根据该文件夹中的图片生成XML文件,或者应该使用
1回复

Android:上传刚拍摄的Bij相机图片

我正在尝试制作一个使用相机拍摄照片并将其发送到我的NAS的应用程序,我设法通过了一个教程来创建一个应用程序,该教程可以拍摄照片,保存照片并将其显示在屏幕上。 另一个教程向我展示了如何通过按屏幕上的“额外”按钮来上传“选定的”图像,这只是我要摆脱这一步骤,而不是显示图片,而是直接将图片发送到我的
4回复

使用Android拍摄的问题(垂直相机|人像)

以下代码显示了相机的垂直预览,它的工作原理..但是! 我在风景中得到了一张照片! :( 我如何垂直构建它? 我在垂直方向上有预览视图,但我无法垂直保存图片。 问候和感谢,弗兰 ONCLICK 预习 拍照
2回复

如何从全尺寸相机拍摄照片? (Android Java)

我无法从相机拍摄图片,然后将其存储为Bitmap对象。 我只能找到以缩略图作为位图的解决方案。 我怎样才能做到这一点? 这是代码: 它以System.out.println(“ ERROR TAKING PICTURE”)结尾; 似乎没有写存储空间的权限。 我该如何更改?
2回复

在为相机拍摄的图像创建文件时获取RuntimeException和NullPointerException

我正在制作一个联系议程应用程序,我需要将使用相机拍摄的照片保存到设备库中。 我一直在关注这个教程: https : //developer.android.com/training/camera/photobasics并查看并尝试了几个修复程序,但似乎都没有。 这是拍照后抛出的错误: