SoFunction
Updated on 2025-04-14

Java to implement text to image requirements

background

need:

  • The text sent by the customer may be spliced ​​into an illegal text picture. At this time, the text review engine cannot be checked and can only be detected by the image review engine. At this time, the text picture needs to be converted into a picture and handed over to the image review engine.
  • It is required to support not only ordinary characters, but also special characters such as ASCII and emoticons.

analyze

  • Use Java's awt user interface toolkit to do it.
  • Different operating systems must download each font package in advance, otherwise the generated pictures will be garbled.

Take centos7 system as an example as follows:

  • View all supported fonts: fc-list.
  • After downloading, be sure to refresh the font: fc-cache -fv.
  • Finally, remember: after refreshing the font, you must restart the Java program, otherwise it will not take effect.

Code

@Slf4j
public class TextUtils {

    /**
      * Text =》Picture
      * Color pictures are not supported at present
      */
    private static final int FONT_SIZE = 24;
    private static final int PADDING = 20;
    private static final Color BACKGROUND_COLOR = ;
    private static final Color TEXT_COLOR = ;
    private static final String TEMP_FILE_PREFIX = "tmp_";
    private static final String IMAGE_SUFFIX = "png";
    private static final String[] PREFERRED_FONTS = {
            "DejaVu Sans Mono",      // Priority use of monospace fonts			"Monospaced",             // Java default monospace font            "Symbola",                // Unicode symbols special fonts            "Segoe UI Symbol",        // Windows symbol font            "Apple Symbols",         // macOS symbol font            "Noto Sans Symbols"      // Google symbol font    };

    public static String convertImage(String text) {
        Path tempFile = null;
        try {
            tempFile = (TEMP_FILE_PREFIX, "." + IMAGE_SUFFIX);
            String filePath = ().toString();
            // Split text lines (\R supports line breaking formats for all different operating systems)            List<String> lines = (("\\R"));
            // Get the best available fonts            Font font = getBestAvailableFont();
            // Create temporary images for calculating size            BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
            Graphics2D tempG = ();
            try {
                (font);
                FontMetrics metrics = ();
                // Calculate the maximum line width and total height                int maxWidth = 0;
                for (String line : lines) {
                    int width = (line);
                    if (width > maxWidth) maxWidth = width;
                }
                int totalHeight = () * ();
                // Create actual image                int imageWidth = maxWidth + 2 * PADDING;
                int imageHeight = totalHeight + 2 * PADDING;
                BufferedImage image = new BufferedImage(
                        imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = ();
                try {
                    // Set rendering parameters                    (RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    (font);
                    (BACKGROUND_COLOR);
                    (0, 0, imageWidth, imageHeight);
                    (TEXT_COLOR);
                    // Draw text lines                    int y = PADDING + ();
                    for (String line : lines) {
                        (line, PADDING, y);
                        y += ();
                    }
                }finally {
                    ();
                }
                //Write to file                (image, IMAGE_SUFFIX, new File(filePath));
            }finally {
                ();
            }
            return filePath;
        }catch (Exception e) {
            ("text convert image error: ", e);
            deleteTempFile(tempFile);
            return null;
        }
    }

    private static Font getBestAvailableFont() {
        GraphicsEnvironment ge = ();
        List<String> availableFonts = (());
        // Find preferred fonts        for (String fontName : PREFERRED_FONTS) {
            if ((fontName)) {
                return new Font(fontName, , FONT_SIZE);
            }
        }
        // Fall back to a wider font support        if (("Symbola")) {
            return new Font("Symbola", , FONT_SIZE);
        }
        // Finally fall back to monospace font        return new Font(, , FONT_SIZE);
    }

    public static void deleteTempFile(Path tempFile) {
        if (tempFile != null) {
            try {
                (tempFile);
            } catch (Exception e) {
                ("Failed to delete temp file: {}", tempFile, e);
            }
        }
    }
}

This is the end of this article about Java's required examples to implement text-to-image content. For more related Java text-to-image content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!