Public voidmark (String Srcimgpath, String Outimgpath, Color Markcontentcolor, string Watermarkcontent,integer degree) {Try {//read the original picture informationFile Srcimgfile =NewFile (Srcimgpath); Image srcimg=Imageio.read (srcimgfile);intSrcimgwidth = Srcimg.getwidth (NULL);intSrcimgheight = Srcimg.getheight (NULL);//Add WatermarkBufferedImage bufimg =Newbufferedimage (Srcimgwidth, Srcimgheight, Bufferedimage.type_int_rgb); Graphics2D g=bufimg.creategraphics (); G.drawimage (Srcimg,0, 0, srcimgwidth, Srcimgheight,NULL);//font font = new Font ("Courier new", Font.plain, N);Font font =NewFont ("Blackbody", Font.Bold, 50); G.setcolor (Markcontentcolor); //set the watermark color based on the background of the pictureG.setfont (font);//int x = Srcimgwidth-getwatermarklength (Watermarkcontent, G)-3;//int y = srcImgHeight-3;//set the text centered on the pictureintx = (Srcimgwidth-getwatermarklength (watermarkcontent, G))/2;inty = SRCIMGHEIGHT/2;//Set watermark Rotationif(NULL!=degree) {G.rotate (Math.toradians (degree), (Double) Bufimg.getwidth ()/2, (Double) bufimg.getheight ()/2);}//7. Set Watermark Text TransparencyfloatAlpha = 0.8f;//transparency; 1.0f is opaqueG.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_atop,alpha));//the contents of the watermark, the first parameter, the coordinate position (x, y) of the text on the picture, followed by two parameters .g.drawstring (watermarkcontent,x, y);//Freeing Resourcesg.dispose ();//Output PictureFileOutputStream Outimgstream =NewFileOutputStream (Outimgpath); Imageio.write (Bufimg,"JPG", Outimgstream); Outimgstream.flush (); Outimgstream.close ();} Catch(Exception e) {e.printstacktrace ();}} Public intgetwatermarklength (String watermarkcontent, graphics2d g) {returnG.getfontmetrics (G.getfont ()). Charswidth (Watermarkcontent.tochararray (), 0, Watermarkcontent.length ());}
Java adds a watermark to a picture