码迷,mamicode.com
首页 > 其他好文 > 详细

生成水印图片

时间:2018-01-27 19:03:14      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:==   net   ext   blog   raw   dir   s2d   设置   背景图片   

/**
* 生成水印背景图片
* @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;
}

生成水印图片

标签:==   net   ext   blog   raw   dir   s2d   设置   背景图片   

原文地址:https://www.cnblogs.com/czgxxwz/p/8366434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!