Add a watermark image or text to an Android Image
The basic idea of adding a watermark to an image is to load the source image, add text or load the watermark image, and save the three parts of the image.
Add watermark image:
Private Bitmap createWaterMaskImage (Context gContext, Bitmap src, Bitmap watermark) {String tag = "createBitmap"; Log. d (tag, "create a new bitmap"); if (src = null) {return null;} int w = src. getWidth (); int h = src. getHeight (); int ww = watermark. getWidth (); int wh = watermark. getHeight (); // create the new blank bitmapBitmap newb = Bitmap. createBitmap (w, h, Config. ARGB_8888); // create a new bitmap Canvas cv = new Canvas (newb) with the same width as SRC; // draw src returns cv. drawBitmap (src, 0, 0, null); // draw src at coordinates 0, 0 // draw watermark 1_cv. drawBitmap (watermark, 20, 20, null); // Add the watermark to the bottom right corner of src // save all clipcv. save (Canvas. ALL_SAVE_FLAG); // save // storecv. restore (); // store return newb ;}
Add text
Public static Bitmap scaleWithWH (Bitmap src, double w, double h) {if (w = 0 | h = 0 | src = null) {return src ;} else {// record the width and height of src int width = src. getWidth (); int height = src. getHeight (); // create a matrix container Matrix matrix = new Matrix (); // calculate the scale float scaleWidth = (float) (w/width ); float scaleHeight = (float) (h/height); // start to scale the matrix. postScale (scaleWidth, scaleHeight); // create a scaled image return Bitmap. createBitmap (src, 0, 0, width, height, matrix, true) ;}} public Bitmap drawTextToBitmap (Context gContext, int gResId, String gText) {Resources resources = gContext. getResources (); float scale = resources. getDisplayMetrics (). density; Bitmap bitmap = BitmapFactory. decodeResource (resources, gResId); bitmap = scaleWithWH (bitmap, 300 * scale, 300 * scale); android. graphics. bitmap. config bitmapConfig = bitmap. getConfig (); // set default bitmap config if none if (bitmapConfig = null) {bitmapConfig = android. graphics. bitmap. config. ARGB_8888;} // resource bitmaps are imutable, // so we need to convert it to mutable one bitmap = bitmap. copy (bitmapConfig, true); Canvas canvas = new Canvas (bitmap); // new antialised Paint = new paint (Paint. ANTI_ALIAS_FLAG); // text color-# 3D3D3D paint. setColor (Color. RED); paint. setTextSize (int) (18 * scale); paint. setDither (true); // get clear image sampling paint. setFilterBitmap (true); // filter some Rect bounds = new Rect (); paint. getTextBounds (gText, 0, gText. length (), bounds); int x = 30; int y = 30; canvas. drawText (gText, x * scale, y * scale, paint); return bitmap ;}