Program background
For the realization of the Cadre Training Platform certificate.
In many places in the network there are watermarks, such as the public number above the picture, Weibo, and this csdn blog above the picture ... So it's a whim to see if you can write a tool class that adds a watermark to a picture.
Program code
Package image;Import Java.awt.Color;Import Java.awt.Font;Import Java.awt.Graphics2D;Import Java.awt.Image;Import Java.awt.image.BufferedImage;Import Java.io.File;Import Java.io.FileOutputStream;Import Javax.imageio.ImageIO;/***@use use Java code to add watermarks to pictures */PublicClasswatermarkutils {/** *@param srcimgpath Source Picture Path *@param tarimgpath saved Picture path *@param watermarkcontent Watermark Content *@param markcontentcolor Watermark Color *@param font Watermark Fonts */PublicvoidAddwatermark (String Srcimgpath, String Tarimgpath, String Watermarkcontent,color markcontentcolor,font Font) {try {Read the original picture information File Srcimgfile =New File (Srcimgpath);Get file Image srcimg = Imageio.read (srcimgfile);Convert files to picturesint srcimgwidth = Srcimg.getwidth (NULL);Get the width of the pictureint srcimgheight = Srcimg.getheight (NULL);Get pictures of highAdd watermark bufferedimage bufimg =New BufferedImage (Srcimgwidth, Srcimgheight, Bufferedimage.type_int_rgb); Graphics2D g = bufimg.creategraphics (); G.drawimage (Srcimg,0,0, Srcimgwidth, Srcimgheight,NULL); G.setcolor (Markcontentcolor);Set the watermark color G.setfont (font) according to the background of the picture;Set fontSet the coordinates of a watermarkint x = srcimgwidth-2*getwatermarklength (Watermarkcontent, G);int y = srcimgheight-2*getwatermarklength (Watermarkcontent, G); g.DrawString (watermarkcontent, x, y);Draw a watermark g.dispose ();Output image FileOutputStream Outimgstream =New FileOutputStream (Tarimgpath); Imageio.write (Bufimg,"JPG", outimgstream); System.out.println ("Add watermark complete"); Outimgstream.flush (); Outimgstream.close (); }catch (Exception e) {Todo:handle Exception}}PublicIntGetwatermarklength (String watermarkcontent, graphics2d g) {Return G.getfontmetrics (G.getfont ()). Charswidth (Watermarkcontent.tochararray (),0, Watermarkcontent.length ()); }PublicStaticvoidMain (string[] args) {Font font =New Font ("Microsoft Jas Black", Font.plain, 35); //Watermark font String srcimgpath="h:/quiet when writing/writing blog/java implementation of the image to add a watermark/s.jpg"; //Source picture address String tarimgpath="h:/quiet when writing/writing blog/java implementation of the image to add a watermark/t.jpg"; //Address to be stored String watermarkcontent="picture source: http://blog.csdn.net/zjq_1314520"; //watermark content Color color=new Color (255,255,255,128); //Watermark Image Color and transparency new Watermarkutils (). Addwatermark (Srcimgpath, Tarimgpath, color, Watermarkcontent,font);}}
Final effect
Add text to a picture with Java implementation