Skip to content

Instantly share code, notes, and snippets.

@t-34400
Created February 11, 2024 15:17
Show Gist options
  • Save t-34400/bd54f3f7c7959abadcee45d1a63b0152 to your computer and use it in GitHub Desktop.
Save t-34400/bd54f3f7c7959abadcee45d1a63b0152 to your computer and use it in GitHub Desktop.
Unity / Android Window PixelCopy Plugin
package com.example.capturewindow;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.PixelCopy;
import android.view.Window;
import java.io.ByteArrayOutputStream;
import com.unity3d.player.UnityPlayer;
public class WindowPixelCopy {
private static final String TAG = WindowPixelCopy.class.getSimpleName();
public byte[] jpegBytes = new byte[0];
public void captureWindow(Activity activity, String gameObjectName, String methodName) {
Window window = activity.getWindow();
View decorView = window.getDecorView();
Rect srcRect = new Rect(0, 0, decorView.getWidth(), decorView.getHeight());
Bitmap bitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);
PixelCopy.request(window, srcRect, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
jpegBytes = baos.toByteArray();
UnityPlayer.UnitySendMessage(gameObjectName, methodName, "");
} else {
Log.e(TAG, "Window pixel copy failed. code=" + copyResult);
}
}, new Handler());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment