【问题标题】:How to display capture image from camera and display in imageview from file path? [duplicate]如何显示来自相机的捕获图像并从文件路径显示在图像视图中? [复制]
【发布时间】:2017-05-12 07:46:39
【问题描述】:

拍照后我的问题,然后 createImageFile .. onActivityResult,照片没有出现在 img_photo 上。如何让 img_photo 出现?

 img_photo = (ImageView) findViewById(R.id.imgPhoto);
        // take a photo from camera
        imgBtnCamera = (ImageButton) findViewById(R.id.imgBtnCamera);
        imgBtnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

                    // Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                    } catch (IOException ex) {
                        // Error occurred while creating the File
                    }

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        Uri photoURI = FileProvider.getUriForFile(PhotoSubmitActivity.this,
                                "com.example.android.fileprovider", photoFile);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    }
                }

            }
        });

创建图片文件

// Create image file
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

onActivityResult

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

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            try {
                Log.v("This is totally working", "Yeah!");
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
                img_photo.setScaleType(ImageView.ScaleType.CENTER_CROP);
                img_photo.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

我在此链接上参加了培训Taking Photos Simply

【问题讨论】:

    标签: android bitmap android-camera


    【解决方案1】:

    我也有同样的问题。但我解决了。 @Driyanto Saputro 在我的代码中看到我在 ImageView 中为保存捕获的图像添加了注释。 另请注意:我正在使用不使用现有相机的自定义相机。 我将下面的代码粘贴到将捕获的图像保存在 imageView 中。

    public void CaptureImage() {
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            private File imageFile;
    
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                try {
                    // Convert byte array into bitmap
                    final Bitmap originalBitmap = MainActivity.decodeSampledBitmapFromByte(getApplicationContext(), data);
    
                    // Rotate Image
                    Matrix rotateMatrix = new Matrix();
                    final Bitmap rotatedBitmap;
                    if (mCameraId == CAMERA_FACING_FRONT) {
                        rotateMatrix.postRotate(270);
                    } else {
                        rotateMatrix.postRotate(90);
                    }
    
                    rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), rotateMatrix, false);
    
                    final File imageFolder;
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
                    } else {
                        imageFolder = new File(Environment.getExternalStorageDirectory() + "/CameraApp/Images");
                    }
    
                    boolean success = true;
                    if (!imageFolder.exists()) {
                        success = imageFolder.mkdirs();
                    }
                    if (success) {
                        java.util.Date date = new java.util.Date();
                        imageFile = new File(imageFolder.getAbsolutePath() + File.separator + getFileNameCustomFormat() + " " + "Image.jpg");
    
                        SavedImagePath = getFileNameCustomFormat() + " " + "Image.jpg";
                        // imageFile.createNewFile();
                    } else {
                        Toast.makeText(getBaseContext(), "Image Not saved", Toast.LENGTH_SHORT).show();
                        return;
                    }
    
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
                    // Save image into gallery
                    if (rotatedBitmap != null) {
                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
                    }
    
                    FileOutputStream file_out = new FileOutputStream(imageFile);
                    file_out.write(outputStream.toByteArray());
                    file_out.close();
                    ContentValues values = new ContentValues();
    
                    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    values.put(MediaStore.MediaColumns.DATA, imageFile.getAbsolutePath());
    
                    getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    
                    Toast.makeText(getApplicationContext(), "Photo Captured", Toast.LENGTH_SHORT).show();
    
                    // Code For Captured Image Save in a ImageView.
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String imagePath = imageFolder.getAbsolutePath() + File.separator + SavedImagePath;
                            Uri myURI = Uri.parse(imagePath);
                            imgBtnThumbnail.setImageURI(myURI);
    
                            Toast.makeText(getApplicationContext(), "Photo Saved on ImageView", Toast.LENGTH_SHORT).show();
                        }
                    });
                    mCamera.startPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    希望对你有帮助。(:

    【讨论】:

      【解决方案2】:

      试试这个方法会有帮助的

      public class MainActivity extends Activity {
      
          // Activity request codes
          private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
          private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
          public static final int MEDIA_TYPE_IMAGE = 1;
          public static final int MEDIA_TYPE_VIDEO = 2;
      
          // directory name to store captured images and videos
          private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
      
          private Uri fileUri; // file url to store image/video
      
          private ImageView imgPreview;
          private VideoView videoPreview;
          private Button btnCapturePicture, btnRecordVideo;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              imgPreview = (ImageView) findViewById(R.id.imgPreview);
              videoPreview = (VideoView) findViewById(R.id.videoPreview);
              btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
              btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
      
              /**
               * Capture image button click event
               */
              btnCapturePicture.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View v) {
                      // capture picture
                      captureImage();
                  }
              });
      
              /**
               * Record video button click event
               */
              btnRecordVideo.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View v) {
                      // record video
                      recordVideo();
                  }
              });
      
              // Checking camera availability
              if (!isDeviceSupportCamera()) {
                  Toast.makeText(getApplicationContext(),
                          "Sorry! Your device doesn't support camera",
                          Toast.LENGTH_LONG).show();
                  // will close the app if the device does't have camera
                  finish();
              }
          }
      
          /**
           * Checking device has camera hardware or not
           * */
          private boolean isDeviceSupportCamera() {
              if (getApplicationContext().getPackageManager().hasSystemFeature(
                      PackageManager.FEATURE_CAMERA)) {
                  // this device has a camera
                  return true;
              } else {
                  // no camera on this device
                  return false;
              }
          }
      
          /**
           * Capturing Camera Image will lauch camera app requrest image capture
           */
          private void captureImage() {
              Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      
              fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
      
              intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
      
              // start the image capture Intent
              startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
          }
      
          /**
           * Here we store the file url as it will be null after returning from camera
           * app
           */
          @Override
          protected void onSaveInstanceState(Bundle outState) {
              super.onSaveInstanceState(outState);
      
              // save file url in bundle as it will be null on scren orientation
              // changes
              outState.putParcelable("file_uri", fileUri);
          }
      
          @Override
          protected void onRestoreInstanceState(Bundle savedInstanceState) {
              super.onRestoreInstanceState(savedInstanceState);
      
              // get the file url
              fileUri = savedInstanceState.getParcelable("file_uri");
          }
      
          /**
           * Recording video
           */
          private void recordVideo() {
              Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
      
              fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
      
              // set video quality
              intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
      
              intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                                                                  // name
      
              // start the video capture Intent
              startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
          }
      
          /**
           * Receiving activity result method will be called after closing the camera
           * */
          @Override
          protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              // if the result is capturing Image
              if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
                  if (resultCode == RESULT_OK) {
                      // successfully captured the image
                      // display it in image view
                      previewCapturedImage();
                  } else if (resultCode == RESULT_CANCELED) {
                      // user cancelled Image capture
                      Toast.makeText(getApplicationContext(),
                              "User cancelled image capture", Toast.LENGTH_SHORT)
                              .show();
                  } else {
                      // failed to capture image
                      Toast.makeText(getApplicationContext(),
                              "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                              .show();
                  }
              } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
                  if (resultCode == RESULT_OK) {
                      // video successfully recorded
                      // preview the recorded video
                      previewVideo();
                  } else if (resultCode == RESULT_CANCELED) {
                      // user cancelled recording
                      Toast.makeText(getApplicationContext(),
                              "User cancelled video recording", Toast.LENGTH_SHORT)
                              .show();
                  } else {
                      // failed to record video
                      Toast.makeText(getApplicationContext(),
                              "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                              .show();
                  }
              }
          }
      
          /**
           * Display image from a path to ImageView
           */
          private void previewCapturedImage() {
              try {
                  // hide video preview
                  videoPreview.setVisibility(View.GONE);
      
                  imgPreview.setVisibility(View.VISIBLE);
      
                  // bimatp factory
                  BitmapFactory.Options options = new BitmapFactory.Options();
      
                  // downsizing image as it throws OutOfMemory Exception for larger
                  // images
                  options.inSampleSize = 8;
      
                  final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                          options);
      
                  imgPreview.setImageBitmap(bitmap);
              } catch (NullPointerException e) {
                  e.printStackTrace();
              }
          }
      
          /**
           * Previewing recorded video
           */
          private void previewVideo() {
              try {
                  // hide image preview
                  imgPreview.setVisibility(View.GONE);
      
                  videoPreview.setVisibility(View.VISIBLE);
                  videoPreview.setVideoPath(fileUri.getPath());
                  // start playing
                  videoPreview.start();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      
          /**
           * ------------ Helper Methods ---------------------- 
           * */
      
          /**
           * Creating file uri to store image/video
           */
          public Uri getOutputMediaFileUri(int type) {
              return Uri.fromFile(getOutputMediaFile(type));
          }
      
          /**
           * returning image / video
           */
          private static File getOutputMediaFile(int type) {
      
              // External sdcard location
              File mediaStorageDir = new File(
                      Environment
                              .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                      IMAGE_DIRECTORY_NAME);
      
              // Create the storage directory if it does not exist
              if (!mediaStorageDir.exists()) {
                  if (!mediaStorageDir.mkdirs()) {
                      Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                              + IMAGE_DIRECTORY_NAME + " directory");
                      return null;
                  }
              }
      
              // Create a media file name
              String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                      Locale.getDefault()).format(new Date());
              File mediaFile;
              if (type == MEDIA_TYPE_IMAGE) {
                  mediaFile = new File(mediaStorageDir.getPath() + File.separator
                          + "IMG_" + timeStamp + ".jpg");
              } else if (type == MEDIA_TYPE_VIDEO) {
                  mediaFile = new File(mediaStorageDir.getPath() + File.separator
                          + "VID_" + timeStamp + ".mp4");
              } else {
                  return null;
              }
      
              return mediaFile;
          }
      }
      

      http://www.androidhive.info/2013/09/android-working-with-camera-api/

      【讨论】:

      • 我收到这个错误:getOutputMediaFileUri(PhotoSubmitActivity.java:252), captureImage(PhotoSubmitActivity.java:175), access$000(PhotoSubmitActivity.java:41), onClick(PhotoSubmitActivity.java:105)
      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多