java解析图片文字,Java解析truetype字体提取每个字符作为图像&它的代码

Is there any java library that can be used to extract each character from a true type font (.ttf)?

Each character of the font, I want to:

Convert it to the image

Extract its code (ex: Unicode value)

Anyone can help to show me some tips on above purpose?

解决方案

This will convert a String to a BufferedImage:

public BufferedImage stringToBufferedImage(String s) {

//First, we have to calculate the string's width and height

BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);

Graphics g = img.getGraphics();

//Set the font to be used when drawing the string

Font f = new Font("Tahoma", Font.PLAIN, 48);

g.setFont(f);

//Get the string visual bounds

FontRenderContext frc = g.getFontMetrics().getFontRenderContext();

Rectangle2D rect = f.getStringBounds(s, frc);

//Release resources

g.dispose();

//Then, we have to draw the string on the final image

//Create a new image where to print the character

img = new BufferedImage((int) Math.ceil(rect.getWidth()), (int) Math.ceil(rect.getHeight()), BufferedImage.TYPE_4BYTE_ABGR);

g = img.getGraphics();

g.setColor(Color.black); //Otherwise the text would be white

g.setFont(f);

//Calculate x and y for that string

FontMetrics fm = g.getFontMetrics();

int x = 0;

int y = fm.getAscent(); //getAscent() = baseline

g.drawString(s, x, y);

//Release resources

g.dispose();

//Return the image

return img;

}

I think there isn't a way to get all the characters, you have to create a String or a char array where you store all the chars you want to convert to image.

Once you have the String or char[] with all keys you want to convert, you can easily iterate over it and convert call the stringToBufferedImage method, then you can do

int charCode = (int) charactersMap.charAt(counter);

if charactersMap is a String, or

int charCode = (int) charactersMap[counter];

if charactersMap is a char array

Hope this helps

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值