Graphics2D Writing Picture Chinese Garbled Code Problem and Its Solution

  • 2021-12-12 04:10:28
  • OfStack

Directory Graphics2D Overview of the causes of the problem in writing pictures in Chinese & Solve the garbled code when Graphics2D displays characters

Graphics2D writing pictures in Chinese garbled codes

Overview

Due to the needs of work, I need to write to pictures. When I write Chinese, there is garbled code. I can't find a lot of information on the Internet. Later, I kept trying and finally found the garbled code caused by the setting problem of name of Font.

Causes of the problem & Solve

The glyph class Font is used to standardize glyph sizes, styles, fonts, and so on used by components. Its constructor:


public Font(String name,int style,int size);
name Indicates the locally available font name style Represents font styles, including Font. PLAIN, Font. BOLD and Font. ITALIC, which correspond to flat, bold and italic respectively. It can be seen that Font name cannot be set casually

See which fonts are supported by the server


   GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fa=ge.getAvailableFontFamilyNames();
        for (String s:fa) {
            System.out.println(s);
        }

If the desired font does not exist on the server, upload it to the server via ftp by downloading it online or copying it from another system (for example, the font file simsun. ttc simsun. ttf) and copy it to the/usr/local/jdk/jre/lib/fonts/directory (jdk installation directory), and then restart the java process.

Test code


        BufferedImage buffImg = ImageIO.read(new File("/tmp/1.jpg"));
        Graphics2D g = buffImg.createGraphics();
        g.setColor(Color.BLACK);
        Font f = new Font(" Song Style ",Font.PLAIN, 30);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(f);
        FontMetrics fm = g.getFontMetrics(f);
        g.drawString(" Medium 31 Countries ", 100, 100);
        ImageIO.write(buffImg, FORMAT, new File("/tmp/test.jpg"));

Graphics2D is garbled when displaying text

Graphics2D is garbled when displaying text. One scheme is to add fonts on the server

One is to change Chinese characters into unicode

The text stored in the database is\ u6388\ u6743\ u7e\ u540d\ uff1a

It still appears on the page that\ u6388\ u6743\ u7e\ u540d\ uff1a is obviously escaped


String s = "\u5ba2\u6237\u7b7e\u5b57\uff1a";
String str = s.replaceAll("\\\\", "");

Now replace 1 with replalaceAll.


Related articles: