Почему я не могу прочитать файлы, созданные основной камерой телефона, пока работает фронтальная камера - PullRequest
0 голосов
/ 26 августа 2018

Я пытаюсь загрузить фотографии, сделанные встроенной камерой, в телефон LG G8. Код работает для фронтальной камеры, но выдает исключение нулевого указателя, если я переключаю его обратно.

static final int DESIRED_WIDTH = 640;
static final int DESIRED_HIGH = 480;

private Bitmap retrieveBitmap(){
    // Get the dimensions of the bitmap
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    //decode only size
    bitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(currentPhotoPath, bitmapOptions);

    //returns 0 x 0
    int photoW = bitmapOptions.outWidth;
    int photoH = bitmapOptions.outHeight;

    // Determine how much to scale down the image
    float scaleFactor = Math.min( (float) photoW/ (float) DESIRED_WIDTH,
            (float)  photoH/ (float) DESIRED_HIGH);

    // Decode the image file into a Bitmap of given size
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    bitmapOptions.inJustDecodeBounds = false;
    bitmapOptions.inSampleSize = (int) scaleFactor;

    //returns null
    Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bitmapOptions);
    return  bitmap;
}

Приложение камеры вызывается, как в в этом примере с использованием метода «Сохранить фотографию в полном размере». Android сообщает об исключении NullPointerException после первого вызова BitmapFactory.decodeFile (), как будто файл, созданный с основной камеры, не существует.

E / BitmapFactory: невозможно декодировать поток: java.lang.NullPointerException

Ответы [ 2 ]

0 голосов
/ 27 августа 2018

Отвечая на мой собственный вопрос: оказывается, телефону нужно некоторое время, прежде чем станут доступны большие картинки.Добавление цикла ожидания заставляет его работать:

    private Bitmap retrieveBitmap(){
    // Get the dimensions of the bitmap
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    //decode only size
    bitmapOptions.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(currentPhotoPath, bitmapOptions);
    int i = 0;
    while( bitmapOptions.outWidth == 0 && bitmapOptions.outHeight == 0){
        //wait for 4 seconds for resource to be available, otherwise fail
        try{
            wait(1000);
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
        BitmapFactory.decodeFile(currentPhotoPath, bitmapOptions);
        i++;
        //give up trying
        if( i == 4) break;
    }

    //returns 0 x 0
    int photoW = bitmapOptions.outWidth;
    int photoH = bitmapOptions.outHeight;

    // Determine how much to scale down the image
    float scaleFactor = Math.min( (float) photoW/ (float) DESIRED_WIDTH,
            (float)  photoH/ (float) DESIRED_HIGH);

    // Decode the image file into a Bitmap of given size
    bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
    bitmapOptions.inJustDecodeBounds = false;
    bitmapOptions.inSampleSize = (int) scaleFactor;

    return  BitmapFactory.decodeFile(currentPhotoPath, bitmapOptions);
}
0 голосов
/ 26 августа 2018

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

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

public class MainActivity extends AppCompatActivity {

    static final int REQUEST_IMAGE_CAPTURE = 1;

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        galleryAddPic();
        ImageView img = findViewById(R.id.img);
        Bitmap bitm = BitmapFactory.decodeFile(mCurrentPhotoPath);
        img.setImageBitmap(bitm);
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }


    public void cameraClick(View v){
        dispatchTakePictureIntent();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...