Skip to content

Instantly share code, notes, and snippets.

@esabook
Created June 4, 2020 16:29
Show Gist options
  • Save esabook/1d584737aad26ccc2a092b9ea970170f to your computer and use it in GitHub Desktop.
Save esabook/1d584737aad26ccc2a092b9ea970170f to your computer and use it in GitHub Desktop.
green screen
class MaskingGenerator extends AsyncTask<ActivityCameraBinding, Void, BitmapDrawable> {
@Override
protected BitmapDrawable doInBackground(ActivityCameraBinding... bindings) {
try {
ActivityCameraBinding b = bindings[0];
int maxDispayW = b.camera.getWidth();
int maxDispayH = b.camera.getHeight();
if (maxDispayH <= 0 || maxDispayW <= 0) return null;
// draw background
Bitmap outerBg = Bitmap.createBitmap(maxDispayW, maxDispayH, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(outerBg);
Paint bg = new Paint();
bg.setStyle(Paint.Style.FILL);
bg.setColor(payloadData.outerBackgroundColor);
c.drawPaint(bg);
// draw masking hole, crop
Drawable maskDrawable = b.overlay.getDrawable();
Bitmap mask = convertToBitmap(maskDrawable,
b.overlay.getWidth(), b.overlay.getHeight());
float maskX = b.overlay.getX();
float maskY = b.overlay.getY();
Paint rectPaint = new Paint();
rectPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
rectPaint.setStyle(Paint.Style.FILL);
rectPaint.setAntiAlias(true);
c.drawBitmap(mask, maskX, maskY, rectPaint);
mask.recycle();
// draw original color, exclude Green color
// The matrix is stored in a single array, and its treated as follows: [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t ]
// When applied to a color [r, g, b, a], the resulting color is computed as (after clamping) ;
// R' = a*R + b*G + c*B + d*A + e;
// G' = f*R + g*G + h*B + i*A + j;
// B' = k*R + l*G + m*B + n*A + o;
// A' = p*R + q*G + r*B + s*A + t;
float[] matrix = {
1, 0, 0, 0, 0, //red
0, 1, 0, 0, 0, //green
0, 0, 1, 0, 0, //blue
0, -1, 0, 1, 0, //alpha
};
ColorMatrixColorFilter removeGreenFilter = new ColorMatrixColorFilter(matrix);
Drawable maskDEx = maskDrawable.getConstantState().newDrawable();
maskDEx.setColorFilter(removeGreenFilter);
Bitmap maskEx = convertToBitmap(maskDEx,
b.overlay.getWidth(), b.overlay.getHeight());
rectPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
c.drawBitmap(maskEx, maskX, maskY, rectPaint);
maskEx.recycle();
// assign to view
BitmapDrawable res = new BitmapDrawable(getResources(), outerBg);
res.setAntiAlias(true);
return res;
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(BitmapDrawable res) {
binding.overlayOuter.setImageDrawable(res);
binding.overlayOuter.setVisibility(View.VISIBLE);
binding.overlay.setVisibility(View.INVISIBLE);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment