your programing

Android Camera Intent : 전체 크기 사진을 얻는 방법?

lovepro 2021. 1. 5. 19:49
반응형

Android Camera Intent : 전체 크기 사진을 얻는 방법?


카메라를 실행하려는 의도를 사용하고 있습니다.

Intent cameraIntent = new Intent(
    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getParent().startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

및 사용 :

Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
photoImage.setImageBitmap(thumbnail);
photoImage.setVisibility(View.VISIBLE);

하지만 썸네일 일 뿐인데 전체 비트 맵을 어떻게 얻습니까? 내 활동을 사용하고 다음을 사용할 수 있음을 알고 있습니다.

Camera.PictureCallback()

그러나 어쨌든 Intent를 사용하여 할 수 있습니까?

감사!

편집하다:

나는 또한 시도했다 :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri uri = data.getData();
    imageView.setImageURI(uri);
}

갤러리에서 선택한 사진에 대해 작동하지만 카메라 의도의 경우 data.getData ()는 null을 반환합니다.


전체 크기의 카메라 이미지를 얻으려면 다음과 같이 임시 파일에 사진을 저장하도록 카메라를 가리켜 야합니다.

    private URI mImageUri;

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File photo;
    try
    {
        // place where to store camera taken picture
        photo = this.createTemporaryFile("picture", ".jpg");
        photo.delete();
    }
    catch(Exception e)
    {
        Log.v(TAG, "Can't create file to take picture!");
        Toast.makeText(activity, "Please check SD card! Image shot is impossible!", 10000);
        return false;
    }
    mImageUri = Uri.fromFile(photo);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
    //start camera intent
    activity.startActivityForResult(this, intent, MenuShootImage);

private File createTemporaryFile(String part, String ext) throws Exception
{
    File tempDir= Environment.getExternalStorageDirectory();
    tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
    if(!tempDir.exists())
    {
        tempDir.mkdirs();
    }
    return File.createTempFile(part, ext, tempDir);
}

그런 다음 이미지 캡처 의도가 작동을 마친 후 imageUri다음 코드 사용 하여 사진을 가져옵니다 .

public void grabImage(ImageView imageView)
{
    this.getContentResolver().notifyChange(mImageUri, null);
    ContentResolver cr = this.getContentResolver();
    Bitmap bitmap;
    try
    {
        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
        imageView.setImageBitmap(bitmap);
    }
    catch (Exception e)
    {
        Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "Failed to load", e);
    }
}


//called after camera intent finished
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
    //MenuShootImage is user defined menu option to shoot image
    if(requestCode==MenuShootImage && resultCode==RESULT_OK) 
    {
       ImageView imageView;
       //... some code to inflate/create/find appropriate ImageView to place grabbed image
       this.grabImage(imageView);
    }
    super.onActivityResult(requestCode, resultCode, intent);
}

PS 코드 필요가 안드로이드 M에 적용되는 새로운 보안 제한에 대한 개정하는 - FileProvider : mImageUri로 포장되어야한다FileProvider


카메라를 열고 이미지를 특정 디렉토리에 저장하십시오.

private String pictureImagePath = "";
private void openBackCamera() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = timeStamp + ".jpg";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
    File file = new File(pictureImagePath);
    Uri outputFileUri = Uri.fromFile(file);
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);               
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
    startActivityForResult(cameraIntent, 1);
}

이미지 처리

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
    File imgFile = new  File(pictureImagePath);
        if(imgFile.exists()){        
       Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
       ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
       myImage.setImageBitmap(myBitmap);

        }
    }

}

이것은 오래된 질문이고 대답이 허용되었지만
내 해결책을 공유하고 싶습니다.
이 경우 임시 파일을 만들 필요가 없습니다.
또한 사용자에게 두 가지를 모두 제공하는 선택기를 만듭니다. 카메라로 사진을 찍거나 갤러리에서 기존 사진을 선택합니다.

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);
    chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.chooseaction));
    Intent[] intentArray = {cameraIntent};
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
    startActivityForResult(chooser, RESULT_LOAD_IMAGE);

여기에서 결과를 검색합니다.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // todo use appropriate resultCode in your case
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == FragmentActivity.RESULT_OK) {
        if (data.getData() != null) {
            // this case will occur in case of picking image from the Gallery,
            // but not when taking picture with a camera
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());

                // do whatever you want with the Bitmap ....           

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            // this case will occur when taking a picture with a camera
            Bitmap bitmap = null;
            Cursor cursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED,
                            MediaStore.Images.ImageColumns.ORIENTATION}, MediaStore.Images.Media.DATE_ADDED,
                    null, "date_added DESC");
            if (cursor != null && cursor.moveToFirst()) {
                Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
                String photoPath = uri.toString();
                cursor.close();
                if (photoPath != null) {
                    bitmap = BitmapFactory.decodeFile(photoPath);
                }
            }

            if (bitmap == null) {
                // for safety reasons you can
                // use thumbnail if not retrieved full sized image
                bitmap = (Bitmap) data.getExtras().get("data");
            }
            // do whatever you want with the Bitmap ....
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

나는 또한 Vicky의 대답을 사용했지만 방향 변경시 손실을 피하기 위해 uri를 번들에 저장해야했습니다. 따라서 장치를 기울인 후 의도에서 결과를 얻지 못하면 uri가 방향 변경에서 살아남지 못했기 때문일 수 있습니다.

static final int CAMERA_CAPTURE_REQUEST = 1;
static final String ARG_CURRENT_PIC_URI = "CURRENT_PIC_URI";


String pictureImagePath = folderName + "/" + imageFileName;
File file = new File(Environment.getExternalStorageDirectory(), pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);

mCurrentPicUri = outputFileUri.getPath();

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE_REQUEST);

활동 결과 코드 :

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == CAMERA_CAPTURE_REQUEST && resultCode == Activity.RESULT_OK) 
  {
    File imgFile = new  File(mCurrentPicUri);
    // do something with your image
    // delete uri
    mCurrentPicUri = "";
  }
}

uri를 번들에 저장하십시오.

@Override
public void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  // save uri to bundle
  outState.putString(ARG_CURRENT_PIC_URI, mCurrentPicUri);
}

생성시 저장된 번들에서 검색 :

if (bundle.containsKey(ARG_CURRENT_PIC_URI))
  mCurrentPicUri = bundle.getString(ARG_CURRENT_PIC_URI);

카메라에서 최대 사진 크기를 캡처하려면이 간단한 단계가 매우 유용하기를 바랍니다.

 public static Camera mCamera;

Camera.Parameters parameters = mCamera.getParameters();
  parameters.getSupportedPictureSizes();
List<Camera.Size> supportedSizes = parameters.getSupportedPictureSizes();
  mSizePicture1 = supportedSizes.get(0);
  int cameraSize = supportedSizes.size();
  mSizePicture2 = supportedSizes.get(cameraSize - 1);

    if (mSizePicture1.height < mSizePicture2.height)
       mSizePicture = supportedSizes.get(cameraSize - 1);
    else
       mSizePicture = supportedSizes.get(0);

parameters.setPictureSize(mSizePicture.width, mSizePicture.height);

Here, the supported size of the each mobile is taken, from that which size is maximum that is fixed as picture size to capture.


Don't use onActivityResult's data. It took me many hours to test different solutions. A camera saves a picture (even if you don't set permissions for camera and card reading in AndroidManifest), but then onActivityResult returns data == null and MediaStore returns wrong path. In these solutions you simply get last gallery image, not your photo.

private Uri photoUri;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    ...
}

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

    if (requestCode == CAMERA_RESULT) {
        if (resultCode == RESULT_OK) {
            if (photoUri != null) {
                image.setImageURI(photoUri);
            }
        }
    }
}

private void showCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getContext().getPackageManager()) != null) {
        File file = null;
        try {
            file = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        photoUri = null;
        if (file != null) {
            photoUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, CAMERA_REQUEST);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    // File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(timeStamp, ".jpg", storageDir);
}

ReferenceURL : https://stackoverflow.com/questions/6448856/android-camera-intent-how-to-get-full-sized-photo

반응형