在Web应用中,常常对图片进行水印处理,用于版权作用。
1.jsp页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'img.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <img alt="ImgServlet" src="ImgServlet"> 27 </body> 28 </html>
2.ImgServlet的java代码
1 package com.zuxia.servlet; 2 3 import java.awt.Graphics; 4 import java.awt.Image; 5 import java.awt.image.BufferedImage; 6 import java.io.IOException; 7 import java.io.PrintWriter; 8 9 import javax.imageio.ImageIO; 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.swing.ImageIcon; 15 16 public class ImgServlet extends HttpServlet { 17 18 19 public void doGet(HttpServletRequest request, HttpServletResponse response) 20 throws ServletException, IOException { 21 22 doPost(request, response); 23 24 } 25 26 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 30 //设置输出到客户端的是一张图片而不是网页 31 response.setContentType("image/jpg"); 32 response.setCharacterEncoding("UTF-8"); 33 //1.获取图片 34 ImageIcon imgIcon=new ImageIcon(super.getServletContext().getRealPath("/")+"/imges/"+"mv.jpg"); 35 36 //ImageIcon imgLogo=new ImageIcon(super.getServletContext().getRealPath("/")+"/imges/火焰.jpg"); 37 //获取高度 38 int height=imgIcon.getIconHeight(); 39 40 //获取宽度 41 int width=imgIcon.getIconWidth(); 42 43 Image img=imgIcon.getImage(); 44 45 46 //2.使用虚拟画布,填充图像 47 BufferedImage bg=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); 48 49 //3.获取虚拟画布的画笔 50 Graphics g=bg.getGraphics(); 51 52 g.drawImage(img,0,0,null); 53 54 g.drawString("博哥制作", 10, 20); 55 56 //g.drawImage(imgLogo.getImage(),50,50,null); 57 //输出到页面 58 ImageIO.write(bg, "png",response.getOutputStream()); 59 60 61 62 63 } 64 65 }