2015-09-12 3 views
0

Я хочу сделать снимок и поместить его в изображение. Мне удалось открыть камеру, и каждый раз, когда я делаю снимок, это позволяет мне взять еще один. Это мой OnCreate метод:Сняв одно изображение, а затем отобразите его в ImageView

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_camera); 
    File photo = dispatchTakePictureIntent(); 
    ImageView imgView = (ImageView) findViewById(R.id.DisplayImageView); 
    if(photo.exists()){ 
     Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath()); 
     imgView.setImageBitmap(myBitmap); 
    } 
} 

Это мой метод взятия фото:

private File dispatchTakePictureIntent() { 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    File photoFile = null; 
    // Ensure that there's a camera activity to handle the intent 
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
     // Create the File where the photo should go 
     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      Toast.makeText(this, "Failed to create the image file!", Toast.LENGTH_SHORT).show(); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 
      startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); 

     } 
    } 
    return photoFile; 
} 

Мне нужно, чтобы вернуться к своей деятельности с камеры после одной фотографии и просмотреть его. Как я могу это сделать?

+0

переопределение 'метод onActivityResult' для получения результата обратно после приема фото –

ответ

1

Вы должны Override onActivityResult() вашей деятельности, чтобы получить изображения и отобразить его в ImageView. Вы должны пробовать изображение в соответствии с вашими потребностями, когда вы получаете его от камеры, а также для предотвращения поворота изображения во время отображения в ImageView, вам нужно искать параметры Exif.

Адрес: onActivityResult().

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    try { 
     if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_TAKE_PHOTO) { 

// in case of taking pic from camera, you have to define filepath already and image get saved in that filepath you specified at the time when you started camera intent.So in your case it will be following 

      String filePath=photoFile.getAbsolutePath(); //photofile is the same file you passed while starting camera intent. 
      if (filePath != null) { 
       int orientation = 0; 
       private Bitmap imageBitmap; 
       try { 
        ExifInterface exif = new ExifInterface(filePath); 
        orientation = exif.getAttributeInt(
          ExifInterface.TAG_ORIENTATION, 1); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       try { 
        final BitmapFactory.Options options = new BitmapFactory.Options(); 
        options.inJustDecodeBounds = true; 
        BitmapFactory.decodeFile(filePath, options); 
        options.inSampleSize = calculateInSampleSize(
          options, reqWidth, rewHeight); 
        options.inJustDecodeBounds = false; 
        imageBitmap = BitmapFactory.decodeFile(filePath, 
          options); 
        if (orientation == 6) { 
         Matrix matrix = new Matrix(); 
         matrix.postRotate(90); 
         imageBitmap = Bitmap.createBitmap(imageBitmap, 
           0, 0, imageBitmap.getWidth(), 
           imageBitmap.getHeight(), matrix, true); 
        } else if (orientation == 8) { 
         Matrix matrix = new Matrix(); 
         matrix.postRotate(270); 
         imageBitmap = Bitmap.createBitmap(imageBitmap, 
           0, 0, imageBitmap.getWidth(), 
           imageBitmap.getHeight(), matrix, true); 
        } else if (orientation == 3) { 
         Matrix matrix = new Matrix(); 
         matrix.postRotate(180); 
         imageBitmap = Bitmap.createBitmap(imageBitmap, 
           0, 0, imageBitmap.getWidth(), 
           imageBitmap.getHeight(), matrix, true); 
        } 
       } catch (OutOfMemoryError e) { 
        imageBitmap = null; 
        e.printStackTrace(); 
       } catch (Exception e) { 
        imageBitmap = null; 
        e.printStackTrace(); 
       } 
      } 
      if (imageBitmap != null) { 
       // set this imageBitmap to your ImageView 
      } 
     } 

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

} 

и это функция выборки

public static int calculateInSampleSize(BitmapFactory.Options options, 
             int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 
    if (height > reqHeight || width > reqWidth) { 
     final int halfHeight = height/2; 
     final int halfWidth = width/2; 
     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 
    return inSampleSize; 
} 
0

Ну в вашей деятельности, что делает startActivityForResult переопределить следующий метод

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { 
     Bundle extras = data.getExtras(); 
     Bitmap imageBitmap = (Bitmap) extras.get("data"); 
     mImageView.setImageBitmap(imageBitmap); 
    } 
} 

Заменить mImageView с ImageView вы хотите, чтобы показать ваше изображение

0

Снимки, сделанные с помощью камеры может быть слишком большим, чтобы показать их непосредственно в ImageView.

Проверьте эту ссылку, чтобы эффективно масштабировать изображения, прежде чем показывать их в ImageView.

Этот код точно такой же, что вы хотите реализовать в вашем приложении:

http://android-er.blogspot.co.at/2012/07/scale-bitmap-efficiently.html?m=1

Смежные вопросы