zoukankan      html  css  js  c++  java
  • 生成水印图片

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

  • 相关阅读:
    Linux基础-4磁盘管理
    Linux基础-3文本处理
    Linux基础-2文件及目录管理
    Linux基础-1使用命令帮助
    解决Eclipse 添加 Tomcat 中的一些问题
    非关系型数据库 -- redis
    Java 学习笔记 五 -- Jedis
    Java 学习笔记 四 -- DBUtils的使用
    Java 学习笔记 三 -- 数据库连接池 Druid
    Java 学习笔记 二 -- JDBC事务
  • 原文地址:https://www.cnblogs.com/czgxxwz/p/8366434.html
Copyright © 2011-2022 走看看