0

我正在尝试在纯白色背景上从印地语中绘制字符并将生成的图像存储为jpeg. 我需要动态调整图像大小,使其适合文本。目前,图像高度通过假设大小为 35 像素(字体大小已设置为 22)来固定。如何固定图像宽度?

到目前为止,我已经尝试将图像宽度设置为 35 像素乘以不同文本行的最大长度。那没有用,保存的图像非常宽。我drawString在 Java 中使用图形类的方法。

创建图像的函数:

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.

        int imgWidth_max = 410;
        int imgHeight_max = 230;
        int fontSize = 22;

        Font f = new Font("SERIF", Font.BOLD, fontSize);

        //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.
        for(int i = 0; i < list.size(); i++) {
            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);
    }

我的问题:

  1. 鉴于用于呈现文本的字体是通用的,我如何获得非拉丁类型字符的宽度?
  2. 有没有办法获得适用于所有 UTF-8 字符的宽度?
4

0 回答 0