To get straight to the point, adding a watermark is very simple, in fact, there are only 3 steps :
1, load the original picture
2, load watermark picture
3, save the picture with the watermark
The principle of implementation is: To get the width of the original picture, and then, a new bitmap, the same width, the new bitmap as a canvas, and then, on the canvas above the painting, painting watermark picture, there is text and then draw text.
The above order must not be disorderly, or you may not see the watermark, or text, because the painting under the original image
The code to draw the watermark is as follows:
private static Bitmap Createwatermaskbitmap (Bitmap src, Bitmap watermark,
int paddingleft, int paddingtop) {
if ( src = null) {return
null;
}
int width = src.getwidth ();
int height = src.getheight ();
Create a Bitmap
Bitmap newbitmap = bitmap.createbitmap (width, height, config.argb_8888);//Create a new bitmap
with the same width as src length Use the picture as the canvas
Canvas Canvas = new Canvas (newbitmap);
Start drawing the original picture
Canvas.drawbitmap (src, 0, 0, NULL) on canvas 0, 0 coordinates;
Draw watermark pictures on canvas
canvas.drawbitmap (watermark, paddingleft, paddingtop, null);
Save
Canvas.save (Canvas.all_save_flag);
Storage
Canvas.restore ();
return newbitmap;
}
The code to draw the text is as follows:
/** * Draw Text to the middle * @param context * @param bitmap * @param text * @param size * @param color * @re Turn */public static Bitmap Drawtexttocenter (context, Bitmap Bitmap, String text, int s
ize, int color) {Paint Paint = new Paint (Paint.anti_alias_flag);
Paint.setcolor (color);
Paint.settextsize (dp2px (context, size));
Rect bounds = new Rect ();
Paint.gettextbounds (text, 0, text.length (), bounds); Return Drawtexttobitmap (context, bitmap, text, Paint, Bounds, (Bitmap.getwidth ()-bounds.width ())/2, (b
Itmap.getheight () + bounds.height ())/2);
/** * Picture on the drawing text/private static Bitmap Drawtexttobitmap (context, Bitmap Bitmap, String text,
Paint Paint, Rect bounds, int paddingleft, int paddingtop) {Config bitmapconfig = Bitmap.getconfig (); Paint.setdither (TRUE); Get a clear Image sample Paint.setfilterbitmap (true);//Filter some if (Bitmapconfig = = null){bitmapconfig = config.argb_8888;
} bitmap = Bitmap.copy (Bitmapconfig, true);
Canvas Canvas = new Canvas (bitmap);
Canvas.drawtext (text, paddingleft, paddingtop, paint);
return bitmap;
}
The effect chart is as follows:
GitHub address is: Https://github.com/chenguo4930/Watermark
Git address is: https://github.com/chenguo4930/Watermark.git
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.