Java implementation to add a watermark to a picture

Source: Internet
Author: User

The original artwork is as follows:




The code is as follows:

Package test;
Import Java.awt.AlphaComposite;
Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import java.awt.RenderingHints;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import Java.io.FileOutputStream;

Import Java.io.OutputStream;
Import Javax.imageio.ImageIO;
Import Javax.swing.ImageIcon;
Import Com.sun.image.codec.jpeg.JPEGCodec;
Import Com.sun.image.codec.jpeg.JPEGEncodeParam;

Import Com.sun.image.codec.jpeg.JPEGImageEncoder; public class ImageMark {/** * add text watermark * @param targetimg target picture path, such as: d://fj.jp * @param presstext watermark text, such as : Xingkong22star * @param fontname font name, such as: Arial @param fontstyle font style, such as bold and italic (font.bold| Font.Italic * @param fontsize font size, in pixels * @param color font * @param x Watermark text offset from the left side of the target picture, if x<0, in the middle * @param y watermark text from the offset on the top side of the target picture, if y<0, in the middle * @param alpha transparency (0.0--1.0, 0.0 is completely transparent, 1.0 is completely opaque) * * p Ublic STATic Boolean Createmark (String filepath,string newfilepath) {float Watermarkalpha = (float) 0.5;
		
		Read the original picture ImageIcon Imgicon = new ImageIcon (FilePath);
		
		Image theimg = Imgicon.getimage ();
		int width = theimg.getwidth (null);

		int height = theimg.getheight (null);
		Create a new blank picture with the same size as the original picture bufferedimage Bimage = bufferedimage (width, height, bufferedimage.type_int_rgb);

		Graphics2D g = bimage.creategraphics ();
		Bimage = G.getdeviceconfiguration (). Createcompatibleimage (width,//height, transparency.translucent);
		G.dispose ();

		 g = Bimage.creategraphics ();
		 To set fonts font font = new Font ("Sansserif", Font.Bold, 18);
		G.setfont (font);
		Sets the foreground color G.setcolor (color.white);
		Set Background color g.setbackground (color.white);

		Painting Original G.drawimage (theimg, 0, 0, NULL);

		Values from 0f-1.0f g.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_atop, Watermarkalpha)); Reprint g.drawstring ("Xingkong22star", Imgicon.geticonwidth ()-Imgicon.geticonheight ()-20);

		Transparency Settings End G.setcomposite (alphacomposite.getinstance (alphacomposite.src_over));
		G.dispose ();
		FileOutputStream out = null;
			try {String newwaterfile = Newfilepath;
			out = new FileOutputStream (newwaterfile);
			JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);
			JPEGEncodeParam param = Encoder.getdefaultjpegencodeparam (bimage);
			Param.setquality (50f, true);
		Encoder.encode (Bimage, param);
			catch (Exception e) {System.out.println ("---build failed---");
		return false;
					Finally {if (out!= null) {try {out.close ();
				out = null;
		The catch (Exception e) {}}} System.out.println ("Complete watermark text Loaded");
	return true;            /** * Print the picture to the picture * * @param iconpath-* watermark file * @param srcimgpath-* Target file * @param targerpath * Save location * @param x *--x coordinates * @par Am y *--y coordinate */public static void MarkimageByicon (String IconPath, String Srcimgpath, String targerpath, Integer degree,int x,int y) {outputst 
        Ream OS = null; 
 
            try {Image srcimg = imageio.read (new File (Srcimgpath)); BufferedImage buffimg = new BufferedImage (Srcimg.getwidth (null), srcimg.getheight (null), Bufferedimag 
 
            E.TYPE_INT_RGB); 
            Get the Brush object//Graphics g= buffimg.getgraphics (); 
 
            Graphics2D g = buffimg.creategraphics (); Sets jagged edge processing for line segments G.setrenderinghint (Renderinghints.key_interpolation, Renderinghints.val 
 
            Ue_interpolation_bilinear); G.drawimage (srcimg.getscaledinstance (Srcimg.getwidth (null), srcimg. GetHeight (null), Image.scale_smoo 
 
            TH), 0, 0, NULL); 
                        if (null!= degree) {//Set watermark rotation g.rotate (Math.toradians (degree), (double) Buffimg.getwidth ()/2, (double) buffimg. GetHeight ()/2); 
 
            The path watermark for the watermark image is generally GIF or PNG, which sets the transparency ImageIcon Imgicon = new ImageIcon (IconPath); 
            Gets the image object. 
 
            Image img = imgicon.getimage (); float alpha = 0.5f; 
 
            Transparency G.setcomposite (Alphacomposite.getinstance (alphacomposite.src_atop, Alpha)); 
 
            Represents the location of the watermark Picture G.drawimage (img, x, y, null); 
 
            G.setcomposite (Alphacomposite.getinstance (alphacomposite.src_over)); 
 
            G.dispose (); 
 
            OS = new FileOutputStream (Targerpath); 
 
            Generate Picture Imageio.write (buffimg, "JPG", OS); System.out.println ("Picture Complete add Icon ...") 
        "); 
        catch (Exception e) {e.printstacktrace (); 
            Finally {try {if (null!= OS) os.close (); 
               catch (Exception e) { E.printstacktrace ();
		}} public static void Main (string[] args) {String FilePath = "D:/fj.jpg";
		String Newfilepath = "D:/fj_water.jpg";
		
		 Imagemark.createmark (Filepath,newfilepath); 
	        String Srcimgpath = "D:/fj.jpg"; 
	        String IconPath = "D:/3.png"; 
	        String Targerpath = "D:/markimagebyicon.jpg";
	Add a watermark to the picture Imagemark.markimagebyicon (IconPath, Srcimgpath, Targerpath, NULL, 800, 730);
 }
}

The results of the operation are as follows:



Watermark Text Effect:





Picture Watermark Effect


Watermark Picture:



After adding:







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.