1. 程式人生 > >生成水印圖片

生成水印圖片

idt throw mat 水印 去除 trac gpo iter() ==

/**
* 生成水印背景圖片
* @param request
* @param response
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
public ModelAndView getSyhtml(HttpServletRequest request,
HttpServletResponse response) throws IOException{
int width = 300;
int height = 200;
String text = request.getParameter("text")==null?"":request.getParameter("text");
String djc=request.getParameter("djc")==null?"":request.getParameter("djc");
String rq=request.getParameter("rq")==null?"":request.getParameter("rq");
String logoPathDir = "/images/printsy";
String logoRealPathDir = request.getSession().getServletContext()
.getRealPath(logoPathDir);
String logImageName = UUID.randomUUID().toString()+".png";
String fileName = logoRealPathDir + File.separator + logImageName;
File file = new File(fileName);
Font font = new Font("黑體", Font.PLAIN, 16);

//創建一個畫布
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//獲取畫布的畫筆
Graphics2D g2 = (Graphics2D)bi.getGraphics();
//設置字體光滑
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,RenderingHints.VALUE_STROKE_DEFAULT);
//開始繪圖
g2.setBackground(new Color(255,255,255));
g2.setPaint(new Color(0,0,0)); //設置背景透明,去除雜色
g2.clearRect(0, 0, width, height);
Color c=new Color(217, 217, 217);
FontMetrics fm = g2.getFontMetrics(font);
int textWidth = fm.stringWidth(text);
int djcWidth = fm.stringWidth(djc);
int rqWidth = fm.stringWidth(rq);
double x = (width - textWidth) / 2;
double djcX=(width - djcWidth) / 2;
double rqX=(width - rqWidth) / 2;
AffineTransform transform = new AffineTransform();
transform.rotate(-30 * Math.PI / 180); // 旋轉圖形-30度
//繪制字符串
g2.setTransform(transform);
g2.setColor(c);
g2.setFont(font);
g2.drawString(text,(int)x-70,140);
g2.setFont(font);
g2.drawString(djc, (int)djcX-70, 175);
g2.setFont(font);
g2.drawString(rq,(int)rqX-70, 205);
try {
ImageIO.write(bi, "png", file);
PrintWriter writer = response.getWriter();
writer.write(logImageName);//返回圖片名字
} catch (IOException e) {
System.out.println("生成水印出錯........");
e.printStackTrace();
}
return null;
}

生成水印圖片