Search code examples
androidcanvasbitmapwatermark

how can I add timestamp in captured photo in android


@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(Calendar.getInstance().getTime());
        Bundle extras = data.getExtras();
        Bitmap src= (Bitmap) extras.get("data");
        int w = src.getWidth();
        int h = src.getHeight();

        Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(src, 0, 0, null);
        canvas.drawText(dateTime , 0, 0, null);
        click_image_id.setImageBitmap(result);
    }
}

It get crashed , if I change and commented canvas implementation like //

Bundle extras = data.getExtras();

Bitmap src= (Bitmap) extras.get("data");

click_image_id.setImageBitmap(src);

it execute view, but i need timestamp in the image , need help experts


Solution

  • You need to create and configure a Paint object and use it in the canvas.drawText(). Try something like this (taken from this article).

    
    private fun drawTextToBitmap(bitmap: Bitmap, textSize: Int = 78, text: String): Bitmap {
    
        val canvas = Canvas(bitmap)
        
        // new antialised Paint - empty constructor does also work
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.BLACK
        
        // text size in pixels
        val scale = resources.displayMetrics.density
        paint.textSize = (textSize * scale).roundToInt().toFloat()
    
        //custom fonts or a default font
        val fontFace = ResourcesCompat.getFont(context, R.font.acrobat)
        paint.typeface = Typeface.create(fontFace, Typeface.NORMAL)
    
    
        // draw text to the Canvas center
        val bounds = Rect()
        //draw the text
        paint.getTextBounds(text, 0, text.length, bounds)
    
        //x and y defines the position of the text, starting in the top left corner
        canvas.drawText(text, x, y, paint)
        return bitmap
    }