Какова правильная точка в моем коде для поворота изображения ландшафта, захваченного в моем приложении? - PullRequest
1 голос
/ 07 мая 2019

У меня нет большого опыта работы с камерой и файлами в целом.Я интегрировал библиотеку CameraKit для захвата изображений, и это мой текущий код:

captureButton.setOnClickListener {

            cameraKitView.captureImage() { _, p1 ->

                val timeStamp = System.currentTimeMillis().toString()
                val fileName = "Dere$timeStamp.jpg"

                val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + "Dere"
                val outputDir = File(path)
                outputDir.mkdir()
                val savedPhoto = File(path + File.separator + fileName)


                try {
                    val outputStream = FileOutputStream(savedPhoto.path)
                    outputStream.write(p1)
                    outputStream.close()
                    mActivity.sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(savedPhoto)
                        )
                    )


                    // Here I'm already loading the image into an mage view for the user to apprve the photo

                    Glide.with(mActivity).load(savedPhoto)
                                .into(mActivity.photoEditorFragment.view!!.photo_editor_image)


                    // at this point I save this photo with some extra details that were collected to the local room database

                    val localImagePost = LocalImagePost(
                        timeStamp.toLong(),
                        location.longitude,
                        location.latitude,
                        savedPhoto.path,
                        "",
                        "",
                        true
                    ) 


                    localImageViewModel.insert(localImagePost)

                    sharedViewModelLocalImagePost.sharedImagePostObject.postValue(localImagePost)


                } catch (e: java.io.IOException) {
                    e.printStackTrace()
                }
            }

}

P1 - это ByteArray.Я уже задал вопрос здесь Могу ли я получить ориентацию фотографии, сделанной в моем приложении, если я ограничу ориентацию действия только портретом в моем манифесте? , но я не могу понять, как и где это сделать.используйте это в моем коде.Создать новый файл ИЗ первого файла, который я только что создал, а затем удалить первый?Или мне просто начать с создания повернутого файла?Я немного растерялся, был бы признателен за любую помощь, спасибо!

1 Ответ

0 голосов
/ 07 мая 2019
  //SOLUTION 1->
  //find the Orientation Using ExifInterface
   try{
        File imageFile = new File(imagePath);
        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(
                            ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL);

 //From the orientation value you can convert(Rotate) image according to orientation and can be set it to the ImageView later
         int rotate = 0;
         switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                 rotate = 270;
                 break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                 rotate = 180;
                 break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                 rotate = 90;
                 break;
          }
        }
   catch (Exception e) {
   }

  // Image rotation //
  Matrix matrix = new Matrix();
  matrix.postRotate(orientation);
  Bitmap cropped = Bitmap.createBitmap(scaled, x, y, width, height, matrix, true);  


// SOLUTION 2
ExifInterface oldExif = new ExifInterface(oldImagePath);
String exifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);

if (exifOrientation != null) {
   ExifInterface newExif = new ExifInterface(imagePath);
  newExif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation);
  newExif.saveAttributes();
}
...