Adding a Text Watermark to a Bitmap

Guy Griv
3 min readJan 13, 2020

--

Photo by Two Paddles Axe and Leatherwork on Unsplash

I was working on a side-project and needed a way to add a text watermark to an Image.

After assessing my options, this is the solution I went with:

Let’s break it down:

These are the options for the watermark.

  1. corner — The corner where we want to place the watermark
  2. textSizeToWidthRatio — The ratio between the text size and the bitmap’s width. The default value of 0.04 gives pleasant results, but you can play with it to find what suits yourself.
  3. paddingToWidthRatio — Similar to the previous section, but determines the padding instead of the text size.
  4. textColor — The text color of the watermark.
  5. shadowColor — The color of the shadow that’ll be added to the text. Can be null if no shadow is needed.
  6. typeface — An optional typeface for the watermark.

Here we’re calculating the coordinates for where to draw the watermark text.

The x position is simpler to calculate. If the selected corner is on the left then the x position is the padding (assuming the text will be drawn to the right of this position. If it’s on the right then the position will be the width of the canvas minus the padding (assuming the text will be drawn to the left of this position).

Calculating the y position is a little more complex, because this position corresponds with the baseline of the text we’re drawing.
When the selected corner is on the bottom then the y position is simply the padding. If it’s on the top then we need to calculate the text height using paint.getTextBounds() and add the requested padding.

Putting it all together.

  1. We’re creating a new Bitmap with the same size as the original.
  2. Creating a Paint we’ll use to draw the watermark text on the canvas.
  3. Setting up the Paint’s various properties according to the WatermarkOptions .
  4. Setting the shadow layer if a shadow color was set in the options. I found that a shadow radius of half the size of the text works well.
  5. Finally, drawing the text on the new Bitmap’s canvas, and returning the result.

Now we can call our function with the default WatermarkOptions like so — addWatermark(originalBitmap, "@grivos"), the result will be:

--

--