Wednesday, March 8, 2017

screenshot method / base64

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Base64;
import android.view.View;

import java.io.ByteArrayOutputStream;

/**
 * <h1>Utilities Class</h1>
 * CommonUtils class under common package provides several useful methods
 * that can be used by any of applications that imports this package
 * such as capturing screenshot and encoding/decoding data from/to Base64.
 *
 * @version 1.0
 */

public class CommonUtils {
    private Context mContext;
    private Activity mActivity;
    private static final int SCALED_PIXEL = 256;

    public CommonUtils(Context context, Activity activity) {
        mContext = context;
        mActivity = activity;
    }

    private Bitmap getScreenshot(boolean fullscreen) {
        View view = mActivity.getWindow().getDecorView().getRootView();
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        if (!fullscreen) {
            bitmap = Bitmap.createScaledBitmap(bitmap, SCALED_PIXEL, SCALED_PIXEL, false);
        }

        return bitmap;
    }

    private byte[] convertBitmap2Bytes(Bitmap bitmap) {
        byte[] byteArray;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byteArray = stream.toByteArray();

        return byteArray;
    }

    private String encodeImg2B64(byte[] image) {
        return Base64.encodeToString(image, Base64.DEFAULT);
    }

    /**
     * This method captures a screenshot and encodes the data to Base64
     * @return String Base64 encoded string data from captured screenshot
     */
    public String getB64FromScreenshot() {
        return encodeImg2B64(convertBitmap2Bytes(getScreenshot(false)));
    }

    /**
     * This method is used to get Base64 decoded byte[] data from given Base64 encoded string data
     * @param screenshot Base64 encoded string data
     * @return data Base64 decoded byte[] data
     */
    public byte[] getScreenshotFromB64(String screenshot) {
        byte[] data = Base64.decode(screenshot, Base64.DEFAULT);
        return data;
    }
}

No comments:

Post a Comment