Java 在背景图上面合成二维码图片并添加文字

/**
     * 分享商品 合成二维码图片
     * @param commodityId
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws WriterException/
     */
    @RequestMapping(value = "/shareMergeImg/{userId}/{sptype}/{commodityId}.png")
    public String shareMergeImg(@PathVariable int userId,@PathVariable int commodityId, @PathVariable int sptype,HttpServletRequest request, HttpServletResponse response) throws IOException, WriterException {
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 0);

            //二维码内容
            String regshareurl = "http://192.168.0.134/api/"+"shareCommodity.html?commodityId=" + commodityId + "&userId=" + userId + "&sptype=" + sptype;
            BitMatrix bitMatrix = new MultiFormatWriter().encode(regshareurl, BarcodeFormat.QR_CODE, 224, 224, hints);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            //生成二维码图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }
            //生成白色背景图
//            BufferedImage WHITE = new BufferedImage(750, 1334, BufferedImage.TYPE_INT_BGR);
//            Graphics g = WHITE.getGraphics();
//            g.setColor(Color.WHITE);
//            g.fillRect(0, 0, 750, 1334);
            //获取背景图
            URL urlBack = new URL("http://aizanzan.oss-cn-beijing.aliyuncs.com/CommodityShareBG/2a99bbde92ad1f746ae88f3b683d5b4.jpg");
            URLConnection connectionBack = urlBack.openConnection();
            connectionBack.setDoOutput(true);
            BufferedImage WHITE = ImageIO.read(connectionBack.getInputStream());

            //查询商品信息
            Map<String, Object> resultMap = new HashMap<>();
            if (1 == sptype) {
                //根据商品ID查询大淘客商品详情
                resultMap = dtkTopClient.finddtksp(commodityId + "", "" + userId).getDataParseEntity(Map.class);
            } else {
                resultMap = dtkTopClient.findhdksp(commodityId + "", "" + userId).getDataParseEntity(Map.class);
            }
            String uri = null;//商品图片路径
            String markContent = "";//商品名称
            BigDecimal Price = new BigDecimal(0);//商品价格
            if (null != resultMap && null != resultMap.get("Pic") && !"".equals(resultMap.get("Pic").toString())) {
                uri = resultMap.get("Pic").toString();
            }
            if (null != resultMap && null != resultMap.get("Title") && !"".equals(resultMap.get("Title").toString())) {
                markContent = resultMap.get("Title").toString();
            }
            if (null != resultMap && null != resultMap.get("Price") && !"".equals(resultMap.get("Price").toString())) {
                Price = new BigDecimal(resultMap.get("Price").toString());
            }
            //商品图片
            URL url = new URL(uri);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            BufferedImage bg = ImageIO.read(connection.getInputStream());
            //在背景图上画 获得背景图片对象
            Graphics2D g2d = WHITE.createGraphics();
            //在背景图上画 二维码
            g2d.drawImage(bg, 42, 261, 666, 666, null);//bg代表图片;x距左;y距右;width宽;height高
            //在背景图上画 商品图片
            g2d.drawImage(image, 40, 1008, 224, 224, null);

            //在背景图上添加文字
            int widthW=WHITE.getWidth(null)==-1?750:WHITE.getWidth(null);
            int heightW= WHITE.getHeight(null)==-1?1334:WHITE.getHeight(null);
            System.out.println(WHITE);

            Color mycolor = new Color(Integer.parseInt("2c2c2c", 16));//字体颜色
            int fontSize = 36;
            g2d.setColor(mycolor);
            g2d.setFont(new Font("PingFang-SC-Bold",Font.BOLD,fontSize)); //字体、字型、字号

            int fontlen = getWatermarkLength(markContent, g2d);
            int textWidth = widthW-42*2;
            int line = fontlen/textWidth;//文字长度相对于图片宽度应该有多少行
            int y = 90 + (line + 1)*fontSize;
            System.out.println("水印文字总长度:"+ fontlen + ",图片宽度:"+ textWidth + ",字符个数:"+ markContent.length());

            //文字叠加,自动换行叠加
            int tempX = 42;
            int tempY = 90;
            int tempCharLen = 0;//单字符长度
            int tempLineLen = 0;//单行字符总长度临时计算
            StringBuffer sb =new StringBuffer();
            for(int i=0; i<markContent.length(); i++) {
                char tempChar = markContent.charAt(i);
                tempCharLen = getCharLen(tempChar, g2d);
                tempLineLen += tempCharLen;
                if(tempLineLen >= textWidth) {
                    //长度已经满一行,进行文字叠加
                    g2d.drawString(sb.toString(), tempX, tempY);
                    sb.delete(0, sb.length());//清空内容,重新追加
                    tempY += fontSize;
                    tempLineLen =0;
                }
                sb.append(tempChar);//追加字符
            }
            g2d.drawString(sb.toString(), tempX, tempY);//最后叠加余下的文字
            g2d.dispose();

            WHITE = drawPrice(WHITE,"¥"+Price,50,tempX,y+27);
            response.setContentType("image/png");
            ImageIO.write(WHITE, "png", response.getOutputStream());
            return "";
        }catch (Exception e){
            e.printStackTrace();
            return e.toString();
        }
    }

    public int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }

    /**
     * 获取水印文字总长度
     *@paramwaterMarkContent水印的文字
     *@paramg
     *@return水印文字总长度
     */
    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),0, waterMarkContent.length());
    }

    private BufferedImage drawPrice(BufferedImage bimage,String Price,int fontSize,int tempX,int tempY){
        Graphics2D gW=bimage.createGraphics();
        Color mycolor = new Color(Integer.parseInt("f73e9b", 16));
        gW.setColor(mycolor);
        gW.setBackground(Color.red);
        gW.setFont(new Font("PingFang-SC-Bold",Font.BOLD,fontSize)); //字体、字型、字号

        gW.drawString(Price,tempX,tempY); //画原价格
        return bimage;
    }

背景图:

Java 在背景图上面合成二维码图片并添加文字

 

合成后:

Java 在背景图上面合成二维码图片并添加文字

上一篇:mybatis源码阅读(七) ---ResultSetHandler了解一下


下一篇:阿里规范 - 五、MySQL 数据库 - (四)ORM映射 - 3 - 【强制】不要用 resultClass 当返回参数,即使所有类属性名与数据库字段一一对应