The Missing Documentation: Using FaceDetector with Files

Sree Raman
AndroidPub
Published in
2 min readMar 31, 2017

I recently had to write a feature which allowed users to upload photos to the app. It was a pretty simple feature but there were two requirements. One, I had to allow the user to rotate the photos. Two, I had to detect if there were any faces in the photos.

To upload, I allowed the user to choose a photo from their device or to take a picture using the camera. Both options would return a File that I can then work with. To detect faces in a photo File object I first need to convert it into a Bitmap. But, I ran into a weird issue. As it turns out, I couldn’t just convert it to any old Bitmap . To detect faces using FaceDetector, I needed to ensure the Bitmap is oriented so the faces are upright and it needs to be configured to use RGB_565 using Bitmap.Config.

For the rotation, instead of rotating the photo in the File, I just rotated the ImageView that I used to preview the photo and kept track of the angle the user wanted to rotate the picture to. Then finally, when it was time to upload, I first detected the number of faces, then rotated the photo and finally uploaded it.

Let’s look at the code:

  • To save on memory usage, you could combine the detectFaces() and rotatePhoto() to use the same Bitmap. I separated it in the example above so it would be easier to digest the code.
  • Like I said earlier, the biggest things to note here is to remember to use a Bitmap config-ed to using RGB_565 and detect faces in the photo before you rotate it.

--

--