来自相机的图像未设置为ImageView ...!

时间:2015-01-21 12:16:33

标签: android image

我创建了android项目。 在我的项目中,当我选择从相机选择的选项然后从中捕获图像并单击确定按钮时,图像将不会显示在ImageView中。

我知道问题是什么,但我不知道它的解决方案......

MainActivity.java

private void selectImage() {
        final CharSequence[] option = { "Take Photo", "Choose from Gallery" };
        AlertDialog.Builder builder = new AlertDialog.Builder(
                User_Registration.this);
        builder.setTitle("Add Photo!");
        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        builder.setItems(option, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (option[item].equals("Take Photo")) {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                            .format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + "_";
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), imageFileName
                            + ".jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);

                } else if (option[item].equals("Choose from Gallery")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                }
            }

        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());
                for (File temp : f.listFiles()) {

                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                            .format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + "_";
                    if (temp.getName().equals(imageFileName)) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions);
                    image.setImageBitmap(bitmap);
                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    // f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePath,
                        null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("path of image from gallery......******************.........",
                        picturePath + "");
                image.setImageBitmap(thumbnail);

            }
        }
    }

我创建的图像名称取决于时间戳,但问题是: 如何检索图片以及如何在ImageView 中设置图片?

2 个答案:

答案 0 :(得分:0)

Error came from here 

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

When you call camera intent you call above `String` for image name:

    String timeStamp = 21 jan 2015 06:00:00; //Some thing like this 
    String imageFileName = "JPEG_" + timeStamp + "_";

Now when `onActivityResult()` is called after clicking the image, you call again:

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String timeStamp= 21 jan 2015 06:00:15; //Some thing like this 
    String imageFileName = "JPEG_" + timeStamp + "_";

Check difference in both File name which is in Seconds..

Stored file name is : *JPEG_21 jan 2015 06:00:00.jpg*;

Your are trying to get a file named: *JPEG_21 jan 2015 06:00:10 .jpg*;

---------------------------------------------------------------------------

///what you can do is : Declare  String imageFileName as Global static String

// onclick camera buttonCode

 imageFileName = "JPEG_" + timeStamp + "_.jpg";
 File f = new File(android.os.Environment.getExternalStorageDirectory(),imageFileName);

//on Activity code 

 for (File temp : f.listFiles()) {
//removethis line           

//  String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") .format(new Date());
//removethis line               
// String imageFileName = "JPEG_" + timeStamp + "_";
    if (temp.getName().equals(imageFileName)) {
             f = temp;
               break;
                    }
                }

答案 1 :(得分:0)

按照此代码..这将有所帮助

 public class CameraPhotoCapture extends Activity {

final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;


Uri imageUri                      = null;
static TextView imageDetails      = null;
public  static ImageView showImg  = null;
CameraPhotoCapture CameraActivity = null;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera_photo_capture);
    CameraActivity = this;

    imageDetails = (TextView) findViewById(R.id.imageDetails);

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

    final Button photo = (Button) findViewById(R.id.photo);



    photo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

          /*************************** Camera Intent Start ************************/ 

            // Define the file-name to save photo taken by Camera activity

            String fileName = "Camera_Example.jpg";

            // Create parameters for Intent with filename

            ContentValues values = new ContentValues();

            values.put(MediaStore.Images.Media.TITLE, fileName);

            values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");

            // imageUri is the current activity attribute, define and save it for later usage 

            imageUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            /**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/


            // Standard Intent action that can be sent to have the camera
            // application capture an image and return it. 

            Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );

             intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

             intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

         /*************************** Camera Intent End ************************/


        }   

    });
}


 @Override
 protected void onActivityResult( int requestCode, int resultCode, Intent data)
    {
        if ( requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if ( resultCode == RESULT_OK) {

               /*********** Load Captured Image And Data Start ****************/

                String imageId = convertImageUriToFile( imageUri,CameraActivity);


               //  Create and excecute AsyncTask to load capture image

                new LoadImagesFromSDCard().execute(""+imageId);

              /*********** Load Captured Image And Data End ****************/


            } else if ( resultCode == RESULT_CANCELED) {

                Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
            }
        }
    }


 /************ Convert Image Uri path to physical path **************/

 public static String convertImageUriToFile ( Uri imageUri, Activity activity )  {

        Cursor cursor = null;
        int imageID = 0;

        try {

            /*********** Which columns values want to get *******/
            String [] proj={
                             MediaStore.Images.Media.DATA,
                             MediaStore.Images.Media._ID,
                             MediaStore.Images.Thumbnails._ID,
                             MediaStore.Images.ImageColumns.ORIENTATION
                           };

            cursor = activity.managedQuery(

                            imageUri,         //  Get data for specific image URI
                            proj,             //  Which columns to return
                            null,             //  WHERE clause; which rows to return (all rows)
                            null,             //  WHERE clause selection arguments (none)
                            null              //  Order-by clause (ascending by name)

                         );

            //  Get Query Data

            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int columnIndexThumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            //int orientation_ColumnIndex = cursor.
            //    getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);

            int size = cursor.getCount();

            /*******  If size is 0, there are no images on the SD Card. *****/

            if (size == 0) {


                imageDetails.setText("No Image");
            }
            else
            {

                int thumbID = 0;
                if (cursor.moveToFirst()) {

                    /**************** Captured image details ************/

                    /*****  Used to show image on view in LoadImagesFromSDCard class ******/
                    imageID     = cursor.getInt(columnIndex);

                    thumbID     = cursor.getInt(columnIndexThumb);

                    String Path = cursor.getString(file_ColumnIndex);

                    //String orientation =  cursor.getString(orientation_ColumnIndex);

                    String CapturedImageDetails = " CapturedImageDetails : \n\n"
                                                      +" ImageID :"+imageID+"\n"
                                                      +" ThumbID :"+thumbID+"\n"
                                                      +" Path :"+Path+"\n";

                    // Show Captured Image detail on activity
                    imageDetails.setText( CapturedImageDetails );

                }
            }   
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        // Return Captured Image ImageID ( By this ImageID Image will load from sdcard )

        return ""+imageID;
    }


     /**
     * Async task for loading the images from the SD card.
     *
     * @author Android Example
     *
     */

    // Class with extends AsyncTask class

 public class LoadImagesFromSDCard  extends AsyncTask<String, Void, Void> {

        private ProgressDialog Dialog = new ProgressDialog(CameraPhotoCapture.this);

        Bitmap mBitmap;

        protected void onPreExecute() {
            /****** NOTE: You can call UI Element here. *****/

            // Progress Dialog
            Dialog.setMessage(" Loading image from Sdcard..");
            Dialog.show();
        }


        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;      


                try {

                    /**  Uri.withAppendedPath Method Description
                    * Parameters
                    *    baseUri  Uri to append path segment to
                    *    pathSegment  encoded path segment to append
                    * Returns
                    *    a new Uri based on baseUri with the given segment appended to the path
                    */

                    uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);

                    /**************  Decode an input stream into a bitmap. *********/
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

                    if (bitmap != null) {

                        /********* Creates a new bitmap, scaled from an existing bitmap. ***********/

                        newBitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);

                        bitmap.recycle();

                        if (newBitmap != null) {

                            mBitmap = newBitmap;
                        }
                    }
                } catch (IOException e) {
                    // Error fetching image, try to recover

                    /********* Cancel execution of this task. **********/
                    cancel(true);
                }

            return null;
        }


        protected void onPostExecute(Void unused) {

            // NOTE: You can call UI Element here.

            // Close progress dialog
              Dialog.dismiss();

            if(mBitmap != null)
            {
              // Set Image to ImageView 

               showImg.setImageBitmap(mBitmap);
            } 

        }

    }

    }