{"id":2186,"date":"2021-05-04T10:28:29","date_gmt":"2021-05-04T02:28:29","guid":{"rendered":"https:\/\/cowmanchiang.me\/wp\/?p=2186"},"modified":"2023-10-31T15:41:35","modified_gmt":"2023-10-31T07:41:35","slug":"java-append-string-with-adaptive-font-size-to-image","status":"publish","type":"post","link":"https:\/\/cowmanchiang.me\/wp\/?p=2186","title":{"rendered":"[Java] Append string with adaptive font size to image"},"content":{"rendered":"<p>Ref: <a href=\"https:\/\/blog.csdn.net\/zengrenyuan\/article\/details\/80281738\">https:\/\/blog.csdn.net\/zengrenyuan\/article\/details\/80281738<\/a><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"\">public static ByteArrayOutputStream encodeWithWaterMark(String content) {\n    if (FRONT_IMAGE == null) {\n        return encode(content);\n    }\n\n    ByteArrayOutputStream os = null;\n\n    try {\n        BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT);\n        BufferedImage backImage = QRCodeUtils.toBufferedImage(matrix);\n\n        int fontSize = 20;\n        String stringContent = &quot;\u9080\u8acbQRCode (\u4e00\u822c)&quot;;\n\n        Font font = new Font(&quot;Noto Sans TC&quot;, Font.PLAIN, fontSize);\n        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);\n        int width = getWordWidth(font, stringContent);\n\n        while (width &gt; WIDTH) {  \/\/if string width \uff1e image width \u2794 use smaller font\n            fontSize = fontSize - 1;\n            font = new Font(&quot;Noto Sans TC&quot;, Font.PLAIN, fontSize);\n            metrics = FontDesignMetrics.getMetrics(font);\n            width = getWordWidth(font, stringContent);\n        }\n\n        Graphics2D g = backImage.createGraphics();\n\n        g.setFont(font);\n        g.setColor(Color.BLACK);\n        \/\/text-align:center \uff06 bottom\n        g.drawString(stringContent, (WIDTH - width) \/ 2, HEIGHT - metrics.getAscent());              \n        g.dispose();\n\n        os = new ByteArrayOutputStream();\n        if (!ImageIO.write(backImage, IMAGE_FORMAT, os)) {\n            throw new IOException(&quot;Could not write an image of format png&quot;);\n        }\n\n    } catch (Exception e) {\n        LOG.error(Constants.EXCEPTION_PREFIX, e);\n    }\n\n    return os;\n}\n\nprivate static BufferedImage toBufferedImage(BitMatrix matrix) {\n    int width = matrix.getWidth();\n    int height = matrix.getHeight();\n    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n    for (int x = 0; x &lt; width; x++) {\n        for (int y = 0; y &lt; height; y++) {\n            image.setRGB(x, y, matrix.get(x, y)\n                               ? BLACK\n                               : WHITE);\n        }\n    }\n    return image;\n}\n\npublic static int getWordWidth(Font font, String content) {\n    FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);\n    int width = 0;\n    for (int i = 0; i &lt; content.length(); i++) {\n        width += metrics.charWidth(content.charAt(i));\n    }\n    return width;\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Ref: https:\/\/blog.csdn.net\/zengrenyuan\/article\/details\/80281738 public static ByteArrayOutputStream encodeWithWaterMark(String content) { if (FRONT_IMAGE == null) { return encode(content); } ByteArrayOutputStream os = null; try { BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT); BufferedImage backImage = QRCodeUtils.toBufferedImage(matrix); int fontSize = 20; String stringContent &hellip; <a href=\"https:\/\/cowmanchiang.me\/wp\/?p=2186\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[51],"tags":[],"class_list":["post-2186","post","type-post","status-publish","format-standard","hentry","category-java"],"_links":{"self":[{"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2186","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2186"}],"version-history":[{"count":5,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2186\/revisions"}],"predecessor-version":[{"id":2191,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2186\/revisions\/2191"}],"wp:attachment":[{"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2186"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2186"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cowmanchiang.me\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2186"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}