Android Clipping Face Class Example Code
- 2021-10-11 19:28:42
- OfStack
Face clipping class
public final class FaceCj {
private static BitmapFactory.Options BitmapFactoryOptionsbfo;
private static ByteArrayOutputStream out;
private static byte[] data;
private static FaceDetector.Face[] myFace;
private static FaceDetector myFaceDetect;
private static int tx = 0;
private static int ty = 0;
private static int bx = 0;
private static int by = 0;
private static int width = 0;
private static int height = 0;
private static float wuchax = 0;
private static float wuchay = 0;
private static FaceDetector.Face face;
private static PointF myMidPoint;
private static float myEyesDistance;
private static List<String> facePaths;
private static String facePath;
public static Bitmap cutFace(Bitmap bitmap, Context context) {
facePaths = null;
BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565; // Parameters for constructing bitmap generation must be 565 . Class name +enum
out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
data = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
BitmapFactoryOptionsbfo);
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
width = bitmap.getWidth();
height = bitmap.getHeight();
myFace = new FaceDetector.Face[5]; // Allocate face array space
myFaceDetect = new FaceDetector(bitmap.getWidth(), bitmap.getHeight(), 5);
int numberOfFaceDetected = myFaceDetect.findFaces(bitmap, myFace);
if (numberOfFaceDetected <= 0) {// FaceDetector Constructing instances and analyzing faces
bitmap.recycle();
return null;
}
facePaths = new ArrayList<String>();
for (int i = 0; i < numberOfFaceDetected; i++) {
face = myFace[i];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance(); // The parameters of face center point and distance between eyes are obtained, and each face is framed
wuchax = myEyesDistance / 2 + myEyesDistance;
wuchay = myEyesDistance * 2 / 3 + myEyesDistance;
if (myMidPoint.x - wuchax < 0) {// Judge whether the left side is out of bounds
tx = 0;
} else {
tx = (int) (myMidPoint.x - wuchax);
}
if (myMidPoint.x + wuchax > width) {// Judge whether the right side is out of bounds
bx = width;
} else {
bx = (int) (myMidPoint.x + wuchax);
}
if (myMidPoint.y - wuchay < 0) {// Judge whether the top is out of bounds
ty = 0;
} else {
ty = (int) (myMidPoint.y - wuchay);
}
if (myMidPoint.y + wuchay > height) {// Judge whether the bottom is out of bounds
by = height;
} else {
by = (int) (myMidPoint.y + wuchay);
}
try {
return Bitmap.createBitmap(bitmap, tx, ty, bx - tx, by - ty);// You can adjust the cutting width and height by yourself here
} catch (Exception e) {
e.printStackTrace();
}
}
bitmap.recycle();
return bitmap;
}
}
Summarize