Skip to main content

How to add a watermark to an image in ImageView in Kotlin Android

How to add a watermark to an image in ImageView in Kotlin Android.

Here's a step-by-step tutorial on how to add a watermark to an image in ImageView in Kotlin Android:

  1. Start by creating a new Android project in Android Studio and open the layout file where you want to display the image with the watermark. This layout file should contain an ImageView element.

  2. In your project's res folder, create a new folder called drawable if it doesn't already exist. Inside the drawable folder, add an image file that will serve as your watermark. Make sure the image file has a transparent background and is the desired size and shape for your watermark.

  3. Open the Kotlin file associated with your layout file (usually named MainActivity.kt) and import the necessary classes:

    import android.graphics.Bitmap
    import android.graphics.Canvas
    import android.graphics.drawable.BitmapDrawable
    import android.graphics.drawable.Drawable
  4. Inside the onCreate method of your activity, get a reference to the ImageView element from the layout file:

    val imageView = findViewById<ImageView>(R.id.imageView)
  5. Load the image that you want to display in the ImageView. You can do this using various methods such as using an image URL, loading from the device storage, or using a resource ID. For simplicity, let's assume you're using a resource ID:

    imageView.setImageResource(R.drawable.your_image)
  6. Create a function to add the watermark to the image. This function should take the original image as a parameter and return a new Bitmap with the watermark added:

    fun addWatermarkToImage(originalImage: Bitmap): Bitmap {
    val watermark = getDrawable(R.drawable.your_watermark) // Replace with your watermark image resource ID
    val bitmap = originalImage.copy(Bitmap.Config.ARGB_8888, true)
    val canvas = Canvas(bitmap)
    watermark.setBounds(0, 0, canvas.width, canvas.height)
    watermark.draw(canvas)
    return bitmap
    }

    Note: You may need to adjust the position and size of the watermark using the setBounds method based on your specific requirements.

  7. Finally, call the addWatermarkToImage function and set the modified Bitmap as the image resource for the ImageView:

    val originalBitmap = (imageView.drawable as BitmapDrawable).bitmap
    val watermarkedBitmap = addWatermarkToImage(originalBitmap)
    imageView.setImageBitmap(watermarkedBitmap)

    This code assumes that the ImageView already has an image loaded. If the ImageView is empty, you'll need to handle the case when imageView.drawable is null.

That's it! You have successfully added a watermark to an image in ImageView using Kotlin in Android.