生成二维码之后,给二维码 上方添加文字(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cd420928908/article/details/85165645

生完二维码之后,获取因为需求 我们需要 给二位吗上方添加 一些文字之类的提示信息: 如果 座位号什么的;

           int fontStyle = 1; //字体风格
           int font = 24; //字体大小
           //用来存放带有logo+文字的二维码图片
           String realPath2 = url+"/new/"+shopName+"/";
           String newImageWithText = realPath2+state+code+"newImg.jpg";//组合生成
           File files = new File(newImageWithText);//组合生成
           if (!files.getParentFile().exists())
               files.getParentFile().mkdirs();
           System.out.println(newImageWithText);
           //带有logo的二维码图片
           String targetImage = path;//组合生成

           String text = "桌号: "+state+"-"+ code;//传参

           //在二维码下方添加文字(文字居中)
           pressText(text, newImageWithText, targetImage, fontStyle, Color.decode("#2d667a"), font) ;

调用 pressText()

 public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize) {

        //计算文字开始的位置
        //x开始的位置:(图片宽度-字体大小*字的个数)/2
        int startX = (WIDTH-(fontSize*pressText.length()))/2 +30;
        //y开始的位置:图片高度-(图片高度-图片宽度)/2
        int startY = HEIGHT-(HEIGHT-WIDTH)/2 - 270;

        try {
            File file = new File(targetImg);
            Image src = ImageIO.read(file);
            int imageW = src.getWidth(null);
            int imageH = src.getHeight(null);
            BufferedImage image = new BufferedImage(imageW, 350, BufferedImage.TYPE_INT_ARGB);//TYPE_INT_ARGB 背景为透明的
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, imageH-210, imageW, imageH, null);
            g.setColor(color);
            g.setFont(new Font(null, fontStyle, fontSize));
            g.drawString(pressText, startX, startY);
            g.dispose();

            FileOutputStream out = new FileOutputStream(newImg);
            ImageIO.write(image, "JPEG", out);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
            System.out.println("image press success");
        } catch (Exception e) {
            System.out.println(e);
        }

这样就将文字和二维码 组合在一起了,至于 放在那里,修改

  int startX = (WIDTH-(fontSize*pressText.length()))/2 +30;
        //y开始的位置:图片高度-(图片高度-图片宽度)/2
        int startY = HEIGHT-(HEIGHT-WIDTH)/2 - 270;
  g.drawImage(src, 0, imageH-210, imageW, imageH, null);

就好了

猜你喜欢

转载自blog.csdn.net/cd420928908/article/details/85165645