1

嘿伙计们,我正在使用我的网络摄像头来模拟模拟器中的摄像头,当我去拍照并选择复选标记按钮以使用图片时,我在尝试将图像显示回我ImageView的应用程序时遇到了一个错误。

这是我的代码:

发起人:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);

功能....

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode == CAMERA_PIC_REQUEST) { 
                if (resultCode == RESULT_OK) {
                   Uri selectedImageUri = data.getData();

                    //OI FILE Manager
               filemanagerstring = selectedImageUri.getPath();

                    //MEDIA GALLERY
               selectedImagePath = getPath(selectedImageUri);


               img.setImageURI(selectedImageUri);

               imagePath.getBytes();

               Bitmap bm = BitmapFactory.decodeFile(imagePath);

               Log.w("Here","error");

                Bitmap bm = BitmapFactory.decodeFile(imagePath);

                ImageView image = (ImageView) findViewById(R.id.gimg1);
                image.setImageBitmap(bm);
            } else if (resultCode == RESULT_CANCELED){

            }
   }
}

我遇到一个runtime error

需要建议和想法!

4

4 回答 4

2

您可以使用以下代码。它功能齐全,还允许您从相机和图库中设置图像。我几乎可以肯定您的运行时错误是“OutOfMemoryError:位图大小超出 VM 预算”,因为我看到您已将捕获的图像直接加载到 imageView。你应该缩放它,请看一下我下面代码中名为 GetScaledBitmap 的方法。如果您仅在将图像加载到图像视图时使用该方法,希望您的代码能够正常工作。完整示例已为您完成,希望对您有所帮助。

package com.tseg.android.mctemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.tseg.android.mctemplate.R;

public class PhotoTake extends Activity {
    Button add1 ;
    ImageView img1 ;
    private static final int ACTIVITY_PHOTOS = 0;
    private static final String PACKAGE = "spine";

    Uri mCapturedImageURI;

    private int photo_count = 0;
    boolean hasPhotos = false;
    Bitmap bitmap;
    String[] paths;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo);

        add1 = (Button) findViewById(R.id.add1);
        img1 = (ImageView) findViewById(R.id.img1);

        add1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ShowDialog(100, 1000);
            }
        });
    }



    void ShowDialog(final int req, final int choose) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("");
        builder.setTitle("Select Photo")
                .setCancelable(false)
                .setNegativeButton("Take Photo",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                    int which) {                                
                                File pictureFileDir = getDir();
                                if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

                                    Log.d("Photo Take", "Can't create directory to save image.");
                                    Toast.makeText(PhotoTake.this , "Can't create directory to save image.",
                                            Toast.LENGTH_LONG).show();
                                    return;
                                }

                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
                                String date = dateFormat.format(new Date());
                                String photoFile = "Picture_" + date + ".jpg";
                                String filepath = pictureFileDir.getPath() + File.separator;
                                File imageFile = new File(filepath , photoFile);

                                ContentValues image = new ContentValues();

                                image.put(Images.Media.TITLE, photoFile);
                                image.put(Images.Media.DISPLAY_NAME, photoFile);
                                image.put(Images.Media.DESCRIPTION, "Accident data Accachment " + date);
                                image.put(Images.Media.DATE_ADDED, date);
                                image.put(Images.Media.DATE_TAKEN, date);
                                image.put(Images.Media.DATE_MODIFIED, date);
                                image.put(Images.Media.MIME_TYPE, "image/jpeg");
                                image.put(Images.Media.ORIENTATION, 0);

                                 File parent = imageFile.getParentFile();
                                 String path = parent.toString().toLowerCase();
                                 String name = parent.getName().toLowerCase();
                                 image.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
                                 image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
                                 image.put(Images.Media.SIZE, imageFile.length());

                                 image.put(Images.Media.DATA, imageFile.getAbsolutePath());

                                 mCapturedImageURI = PhotoTake.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);


                                Intent intent = new Intent(
                                        MediaStore.ACTION_IMAGE_CAPTURE);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                        mCapturedImageURI);

                                startActivityForResult(intent, req);

                            }
                        })
                .setPositiveButton("Choose Existing",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);

                                startActivityForResult(Intent.createChooser(
                                        intent, "Complete action using"),
                                        choose);
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

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

        // From camera

        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            if (mCapturedImageURI != null) {
                img1.setImageBitmap(getScaledBitmap(mCapturedImageURI));;
                System.out.println("Onactivity Result uri = " + mCapturedImageURI.toString());
            } else {
                Toast.makeText(PhotoTake.this, "Error getting Image",
                        Toast.LENGTH_SHORT).show();
            }

        }

        //From gallery
        if (requestCode == 1000) {
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImage = data.getData();
                System.out.println("Content Path : " + selectedImage.toString());

                if (selectedImage != null) {
                    img1.setImageBitmap(getScaledBitmap(selectedImage));
                } else {
                    Toast.makeText(PhotoTake.this, "Error getting Image",
                            Toast.LENGTH_SHORT).show();
                }           
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(PhotoTake.this, "No Photo Selected",
                        Toast.LENGTH_SHORT).show();
            }
        }

    }

    public Bitmap getBitmap(String path) {
        Bitmap myBitmap = null;
        File imgFile = new File(path);
        if (imgFile.exists()) {
            myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        }
        return myBitmap;
    }


    public String getPath(Uri photoUri) {

        String filePath = "";
        if (photoUri != null) {
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(photoUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        }
        return filePath;
    }

    private File getDir() {
        File sdDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return new File(sdDir, "SpineAttachments");
    }

    private Bitmap getScaledBitmap(Uri uri){
        Bitmap thumb = null ;
        try {
            ContentResolver cr = getContentResolver();
            InputStream in = cr.openInputStream(uri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize=8;
            thumb = BitmapFactory.decodeStream(in,null,options);
        } catch (FileNotFoundException e) {
            Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show();
        }
        return thumb ; 
    }
}
于 2013-10-08T01:39:29.180 回答
2
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){

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

        ImageView image = (ImageView) findViewById(R.id.gimg1);

        image.setImageBitmap(image);
}
于 2013-10-08T01:14:07.827 回答
1
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){

        Bitmap image = (Bitmap) data.getExtra("data");
        image_taken.setImageBitmap(image);
}

你打电话,而它data.getData()应该data.getExtra("data")是你将放的dataintentbitmap

于 2013-10-08T01:17:56.270 回答
0

单击按钮并在 imageview 中设置商店图像的非常简单的方法。

`公共类 MainActivity 扩展 Activity {

private static final int CAMERA_PIC_REQUEST = 22;

Uri cameraUri;

Button BtnSelectImage;
private ImageView ImgPhoto;
private String Camerapath ;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImgPhoto = (ImageView) findViewById(R.id.imageView1);

    BtnSelectImage = (Button) findViewById(R.id.button1);
    BtnSelectImage.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            try {
                   Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                   startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
            }
        }
    });

}


@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    try {
        switch (requestCode) {
       case CAMERA_PIC_REQUEST:
            if (resultCode == RESULT_OK) {
                try {
                      Bitmap photo = (Bitmap) data.getExtras().get("data"); 

                      ImgPhoto.setImageBitmap(photo);    

                } catch (Exception e) {
                    Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
            break;
          default:
            break;
        }
    } catch (Exception e) {
    }
}

}`

设置此清单。

<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>

于 2014-07-19T07:13:27.167 回答