code: private static int getScaleFactor(ImageMetadata metadata, int maxPixels) {
          int scale = 1;
          int scaledW = metadata.getW();
          int scaledH = metadata.getH();
          while (scaledW * scaledH > maxPixels) {
              scale *= 2;
              scaledH /= 2;
              scaledW /= 2;
          }
          return scale;
      }
docs: Calculating scale factor with limit of pixel amount
  
  @param metadata  image metadata
  @param maxPixels limit for pixels
  @return scale factor