Home » Android » java – Make sure photos are saved with the same orientation they were taken?

java – Make sure photos are saved with the same orientation they were taken?

Posted by: admin May 14, 2020 Leave a comment

Questions:

For some reason, my camera app saves all photos rotated 90 degrees (pictures only look right when taken with camera on landscape mode) I believe onPictureTaken should rotate photos automatically but I read there is a problem with Samsung devices (I haven’t been able to test it on another brand so I don’t know if it’s the case). This is my code:

   public void onPictureTaken(byte[] data, Camera camera) {
      // Generate file name
      FileOutputStream outStream = null;
      outStream = new FileOutputStream(filePath);
      outStream.write(data);
      outStream.close();

I was thinking it could be fixed by checking the orientation and rotating the byte array but there must be a more straightforward way to do it since handling byte arrays is a pain.
How can I make sure photos are saved matching the orientation they were taken?

How to&Answers:

Try something like this:

int orientation = Exif.getOrientation(data);
Log.d("#", "onPictureTaken().orientation = " + orientation);
if(orientation != 0) {
     Bitmap bmpSrc = BitmapFactory.decodeByteArray(data, 0, data.length);
     Bitmap bmpRotated = CameraUtil.rotate(bmpSrc, orientation);
     bmpSrc.recycle();


       try {

             FileOutputStream localFileOutputStream = new FileOutputStream(filePath);
             bmpRotated.compress(Bitmap.CompressFormat.JPEG, 90,localFileOutputStream);
             localFileOutputStream.flush();
             localFileOutputStream.close();
             bmpRotated.recycle();

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

      } else {

          try {

               FileOutputStream localFileOutputStream = new FileOutputStream(filePath);
               localFileOutputStream.write(data);
               localFileOutputStream.flush();
               localFileOutputStream.close();

               } catch (IOException localIOException)
                  {
                                        Log.e("#",localIOException.getMessage());
                  }
   }

Answer:

There are different ways to get your image, as data, as stream, as file, also it is different for camera and gallery and other apps. For each of them you have another way to access the orientation tag. Once you have the orientation, you can rotate your image.

You – or for that matter everyone – should really get a Nexus, they are nice and rotate the image for you and set orientation to 0, while the lazy ones like Samsung just store the image and set the orientation tag. 😉