`
simen_net
  • 浏览: 300433 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

JAVA 取字模测试类

 
阅读更多

      最近有个需求要取汉字的字模,但是大部分都是C++\Delphi的实现,参考其他范例也实现了一个Delphi取模的方法,但感觉不是非常方便,尤其是在文字的缩放,变形的方面。JAVA里面图片处理的类貌似非常方便,于是也想对照写了一个测试类,非常好用。

      基本思路:根据汉字字体等参数将汉字绘到64X64的图层上,然后分将该图层分成很想16X16的图片。然后对每个图片上的每个像素点取值相加,如果大于阀值则标记该点。这样循环取出16X16的点阵。具体实现的时候可以根据实际需要将图层分辨率、取模比例等进行调整,并且也可以使用JAVA的图像处理方法对汉字进行缩放等。本类中只实现了对汉字的横向、纵向缩放。下面是实现类:

 

package com.strong;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class JavaZiMo {

  private static int intKuan = 64;
  private static int intGao = 64;
  private static int intSuoFangKuan = 1; // 横向缩放比例如 1.01 0.9
  private static int intSuoFangGao = 1; // 纵向缩放比例如 1.01 0.9
  private static int intFaZhi = -16; // 显示阀值
  private static String strShuRu = "胡"; // 待取字模
  private static String strZiTi = "文泉驿正黑"; // 待取字体

  public JavaZiMo() {
  }

  public static void main(String[] args) {
    BufferedImage image = new BufferedImage(intKuan, intGao, BufferedImage.TYPE_INT_BGR);
    Graphics2D g = image.createGraphics();
    Font myFont = new Font(strZiTi, Font.BOLD, 64); // 定义字体样式
    g.setFont(myFont); // 设置字体
    g.fillRect(0, 0, intKuan, intGao); // 绘制背景
    g.setColor(new Color(0, 0, 0)); // 设置字体颜色
    g.scale(intSuoFangKuan, intSuoFangGao); // 设置缩放
    g.drawString(strShuRu, 0, 54);
    g.dispose();
    // 生成图片文件
    // File f1 = new File("/tmp/11.jpg");
    // try {
    // ImageIO.write(image, "JPG", f1);
    // } catch (IOException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    BufferedImage bi[] = new BufferedImage[16 * 16];
    int intDianZhen[] = new int[16 * 16];
    for (int i = 0; i < 16; i++) {
      for (int j = 0; j < 16; j++) {
        bi[i * 16 + j] = image.getSubimage(i * 4, j * 4, 4, 4);
      }
    }
    for (int i = 0; i < bi.length; i++) {
      int intD = 0;
      for (int j = 0; j < 4; j++) {
        for (int k = 0; k < 4; k++) {
          intD += bi[i].getRGB(j, k);
        }
      }
      intDianZhen[i] = intD;
    }
    // intDianZhen是实际的像素值数组,为了方便使用下面再用一个循环取字模,实际可以和上面合并
    for (int i = 0; i < 16; i++) {
      StringBuffer sb = new StringBuffer();
      for (int j = 0; j < 16; j++) {
        if (intDianZhen[i + j * 16] < intFaZhi) {
          sb.append("■");
        } else {
          sb.append("-");
        }
      }
      System.out.println(sb.toString());
    }
  }
}

 运行后在控制台输出如下:

----■■----------
----■■---■■■■■■■
----■■---■■■■■■■
■■■■■■■■■■■--■■■
■---■■--■■■--■■■
----■■---■■■■■■■
----■■---■■--■■■
--■■■■■■-■■--■■■
--■■--■■-■■■■■■■
--■■--■■-■■■■■■■
--■■--■■-■■--■■■
--■■■■■■■■■--■■■
--■■--■■■■■--■■■
--■■--■■■■---■■■
-----■■■■--■■■■■
------■■----■■--
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics