java - 字体显示不正确 - Java

标签 java fonts awt

我有一些英语单词已翻译成泰米尔语。任务要求我展示它们。下面给出了一个示例行。第一行和第二行是泰米尔语,最后一行是孟加拉语。

> unpopular ஜனங்கலால் வெறுக்கப்பட்ட             ¤µ£»ªÀ»õu 
inactive    ஜடமான           ö\¯»ØÓ
doctor  வைத்தியர்           ©¸zxÁº
apart   வேறாக           uµ

如果您注意到上面的内容,某些行中的文本无法正确呈现,因为它是用自定义字体编写的。自定义字体可以从here下载。我的问题:
1. 所有泰米尔字体(自定义和预加载)均已安装。所有文本均无法正确显示。为什么?
2.我加载自定义字体的方式有问题吗?
3. 在上面的行中,第二列是预加载的字体,而第三列是用自定义字体编写的。第三列看起来不像是Unicode,这就是为什么应用任何字体也会失败的原因。这是怎么回事?

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;

/* This is the imageMaker class.
 * It loads a plain white image, writes text taken from another file
 * and creates a new image from it.
 * 
 * Steps: 
 * 1. A plain white image is loaded.
 * 2. Text is taken from a file.
 * 3. Text is written to the image.
 * 4. New image is created and saved.
 */

public class imgMaker_so {

    /**
     * @param args
     */

    private static String tgtDir = "YOUR_tgt directory to store images goes here";
    private static String csvFile = "csv file goes here";
    private static int fontSize = 22;  //default to a 22 pt font.

    private static Font f;
    private static String fontName = "WTAM001"; 

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //Step 0. Read the image.
        //readPlainImage(plainImg);

        //Step 0.a: Check if the directory exists. If not, create it.
        File tgtDir_file = new File(tgtDir);
        if(!tgtDir_file.exists()) { //this directory does not exist.
            tgtDir_file.mkdir();
        }

        Font nf = null;
        try {
            nf = Font.createFont(Font.TRUETYPE_FONT, new File("C:\\Windows\\Fonts\\" + fontName + ".ttf"));
        } catch (FontFormatException | IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        }

        if(nf != null) {
            f = nf.deriveFont(Font.BOLD, fontSize);
        }

        if(f == null) {
            System.out.println("Font is still null.");
        }

        //Step 1. Read csv file and get the string.
        FileInputStream fis = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(new File(csvFile));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String temp = "\u0b85";
        System.out.println(temp.length());
        for(int i = 0; i < temp.length(); i++) {
            System.out.print(temp.charAt(i));
        }

        //SAMPLE CODE ONLY. CHECK IF IT CAN PRINT A SINGLE CHARACTER IN FONT.
        BufferedImage img = new BufferedImage(410, 200, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 410, 200);

        System.out.println("String being printed = " + temp.codePointAt(0));
        g.setColor(Color.BLACK);
        g.setFont(f);
        if(f.canDisplay('\u0b85')) {
            System.out.println("Can display code = \u0b85");
        } else {
            System.out.println("Cannot display code = \u0b85");
        }
        g.drawString(temp, 10, 35);         

        //g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
        g.dispose();

        try {
            ImageIO.write(img, "jpeg", new File(tgtDir + "\\" + "a.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("File written successfully to a");

        //System.out.println("Cat,,बिल्ली,,,");

        if(fis != null) {
            try {
                br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            } catch (UnsupportedEncodingException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                System.out.print("Unsupported encoding");
            }

            String line = null;
            if(br != null) {
                try {
                    while((line = br.readLine()) != null) {
                        if(line != null) {
                            System.out.println("Line = " + line);
                            List<String> word_translation = new ArrayList<String>();
                            parseLine(line, word_translation);  //function to parse the line.
                            //printImages(word_translation);
                            if(word_translation.size() > 0) {
                                printImages_temp(word_translation);
                            }
                            //now that images have been read, read the plain image afresh.
                            //readPlainImage(plainImg);
                            word_translation.clear();
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void printImages_temp(List<String> list) {

        /* Function to print translations contained in list to images.
         * Steps:
         * 1. Take plain white image.
         * 2. Write English word on top.
         * 3. Take each translation and print one to each line.
         */

        String dest = tgtDir + "\\" + list.get(0) + ".jpg";  //destination file image.

        //compute height and width of image.
        int img_height = list.size() * 35 + 20;
        int img_width = 0;
        int max_length = 0;
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).length() > max_length) {
                max_length = list.get(i).length();
            }
        }
        img_width = max_length * 20;

        System.out.println("New dimensions of image = " + img_width + " " + img_height);

        BufferedImage img = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, img_width, img_height);

        //image has to be written to another file. Do not write English word, which is why list starts iteration from 1.
        for(int i = 1; i < list.size(); i++) {
            System.out.println("String being printed = " + list.get(i).codePointAt(0));
            g.setColor(Color.BLACK);
            g.setFont(f);
            g.drawString(list.get(i), 10, (i + 1) * 35);            
        }

        //g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
        g.dispose();

        try {
            ImageIO.write(img, "jpeg", new File(dest));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("File written successfully to " + dest);
    }

    public static void purge(String line) {
        //This removes any inverted commas and tabs from the line apart from trimming it.
        System.out.println("Line for purging = " + line);
        int fromIndex = line.indexOf("\"");
        //System.out.println("from index = " + fromIndex);
        if(fromIndex != -1) {
            line = line.substring((fromIndex + 1));
            int toIndex = line.lastIndexOf("\"", line.length() - 1);
            if(toIndex != -1) {
                line = line.substring(0, (toIndex));
            }
        }
        line.replaceAll("\t", " ");
        line.trim();
        System.out.println("Line after purging = " + line);
    }

    public static void parseLine(String line, List<String> result) {

        /* 
         * This function parses the string and gets the different hindi meanings.
         */

        //int index = line.indexOf(",");
        //int prev_index = 0;

        String[] arr = line.split(",");
        List<String> l = new ArrayList<String>(Arrays.asList(arr));

        for(int i = 0; i < l.size(); i++) {
            if(l.get(i).isEmpty()) {  //if the string at position i is empty.
                l.remove(i);
            }
        }

        for(int i = 0; i < l.size(); i++) {  //inefficient copy but should be short.
            String ith = l.get(i).trim();
            if(!(ith.isEmpty())) {   //add a string to result only if it is non-empty.
                //in some entries, there are commas. they have been replaced with !?. find them and replace them.
                if(ith.contains("!?")) {
                    //System.out.println(r + " contains !?");
                    String r = ith.replace("!?", ",");
                    result.add(r);
                } else if(ith.contains("\n")) {
                    String r = ith.replace("\n", " ");
                    System.out.println("found new line in " + ith);
                    result.add(r);
                } else {
                    result.add(ith);
                }
            }
        }

        for(int i = 0; i < result.size(); i++) {
            System.out.println("Result[" + i + "] = " + result.get(i));
        }

        //System.out.println("Line being printed = " + line);
    }
}

以上文字由专业翻译人员撰写。那么,这里有我缺少的东西吗?

最佳答案

  • 使用 API Font.canDisplay 中的方法测试具体字体

  • 需要在 Unicode form 中进行测试(用于混合几种语言的字符(泰米尔语和孟加拉语))

  • 请您发布 SSCCE,并使用使用的字体和 can be based on

关于java - 字体显示不正确 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607158/

相关文章:

java - 如何让这个类调用另一个类

java - 从大量 Swing 文本字段收集数据

java - 通过GSON将类中的成员字段映射转换为JSON

pdf - 更改 PDF 文档中的字体大小?

fonts - 字体文件的正确 MIME 类型是什么?

java - 如何从声明 JFrame 的类之外的类中关闭 JFrame

java - 如何使用 jSoup 从 Java 模拟 Web 浏览器

java - 运行 sbt 测试套件两次会导致 jdbc 驱动程序未找到错误

html - 字体似乎不起作用

java - 自定义 FocusTraversalPolicy 类 Java Swing