java生成文字图片和文字对齐

/**
* 根据提供的文字生成jpg图片
*
* @param s
* String 文字
* @param align
* 文字位置(left,right,center)
* @param y
* y坐标
* @param width
* 图片宽度
* @param height
* 图片高度
* @param bgcolor
* Color 背景色
* @param fontcolor
* Color 字色
* @param font
* Font 字体字形字号
* @param jpgname
* String jpg图片名
* @return
*/
private static boolean createJpgByFontAndAlign(String s, String align, int y, int width, int height,
Color bgcolor, Color fontcolor, Font font, String jpgname) {
try { // 宽度 高度
BufferedImage bimage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.setColor(bgcolor); // 背景色
g.fillRect(0, 0, width, height); // 画一个矩形
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON); // 去除锯齿(当设置的字体过大的时候,会出现锯齿)
g.setColor(fontcolor); // 字的颜色
g.setFont(font); // 字体字形字号

int size = font.getSize(); //文字大小
int x = 5;
if(align.equals("left")){
x = 5;
} else if(align.equals("right")){
x = width - size * s.length() - 5;
} else if(align.equals("center")){
x = (width - size * s.length())/2;
}
g.drawString(s, x, y); // 在指定坐标除添加文字
g.dispose();
FileOutputStream out = new FileOutputStream(jpgname); // 指定输出文件
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param); // 存盘
out.flush();
out.close();
} catch (Exception e) {
System.out.println("createJpgByFont Failed!");
e.printStackTrace();
return false;
}
return true;
}

public static void main(String[] args) {
createJpgByFontAndAlign("生成图片", "right", 15, 200, 25, Color.white, Color.black,
new Font(null, Font.BOLD, 12), "E:/right.jpg");
createJpgByFontAndAlign("生成图片", "center", 15, 200, 25, Color.white, Color.black,
new Font(null, Font.BOLD, 12), "E:/center.jpg");
createJpgByFontAndAlign("生成图片", "left", 15, 200, 25, Color.white, Color.black,
new Font(null, Font.BOLD, 12), "E:/left.jpg");
}

生成的图片如下,目前生成的文字为全角字符,半角字符会发生错位
居中对齐[img]http://dl.iteye.com/upload/attachment/0078/0908/1b02ff5f-5b30-3b32-b522-7920ab1e9074.jpg[/img]

左对齐[img]http://dl.iteye.com/upload/attachment/0078/0910/2e3d4bda-0177-3587-b3c7-7f919770f383.jpg[/img]

右对齐[img]http://dl.iteye.com/upload/attachment/0078/0912/7836d344-d608-35be-bf29-ab8c0c11945e.jpg[/img]

现在又一个问题想请教,当生成的文字中出现全角与半角字符都存在的情况应该如何定位?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值