Steps:
1. Build a Web project [complete]
2. Writing Web pages (containing pictures)
3. Write a filter to add a watermark to all the requested pages
Core code:
/**
* All requests are subject to this filtering method
*/
public void DoFilter (ServletRequest req, servletresponse Res,
Filterchain chain) throws IOException, Servletexception {
HttpServletRequest request = (httpservletrequest) req;
1. Get the context path/watermark
String path = Request.getcontextpath ();
2. Get the request path/watermark/images/img1.jpg
String RequestUri = Request.getrequesturi ();
3. Get the physical path to the picture
This can also get the project's release path
Realpath+requesturi can get the full path of the picture
String Realpath=request.getrealpath ("/");
Left and right slashes are not affected
String Realpath = Request.getsession (). Getservletcontext (). Getrealpath (
"/")
+ RequestUri
. substring (requesturi.indexof (path) + path.length ());
4. Read the picture from the request into the byte buffer
FileInputStream fis = new FileInputStream (Realpath);
Create a picture buffer
byte[] Imagebuff = new byte[fis.available ()];
Read in picture byte data
Fis.read (Imagebuff);
5. Get the original height and width of the picture
Image image = new ImageIcon (imagebuff). GetImage ();
int imgwidth = Image.getwidth (null);
int imgheight = Image.getheight (null);
6. Synthesizing text information into a picture buffer
BufferedImage bufferedimage = new BufferedImage (ImgWidth, ImgHeight,
BUFFEREDIMAGE.TYPE_INT_RGB);
Graphics g = bufferedimage.creategraphics ();
Loading the image data in
G.drawimage (image, 0, 0, imgwidth, imgheight, NULL);
Draw text
G.setcolor (color.red); Set Text color
Font f = new Font ("script", Font.Italic, 30); Create font, font style, font size
G.setfont (f); Set font
g.DrawString ("Senior Java Engineer", 300, 900);
g.DrawString ("qq:425336980", 320, 940);
G.dispose ();
7. Converting the image of a buffer to a byte array
Bytearrayoutputstream out = new Bytearrayoutputstream ();
JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);
Encode data from an image buffer into JPEG format
Encoder.encode (BufferedImage);
Convert images in JPEG format to byte arrays
byte[] Resultdata = Out.tobytearray ();
Out.close ();
8. Send the converted JPEG byte array data directly to the servlet response stream for output
Res.setcontentlength (resultdata.length);
Res.getoutputstream (). write (Resultdata);
Res.getoutputstream (). Close ();
Chain.dofilter (req, res);
}
Case Download: Http://pan.baidu.com/s/1pJiTePH
Batch image watermark processing using Java technology