请教一个问题。
我在把文字写入图片时,如果字符串为unicode编码的话,生成的图片部分字符乱码,不过这个字符串如果使用log4j编码为utf-8打印到日志文件时是正常的,但在console控制台打印出来跟图片是一样的,也是部分字符乱码那。
但在debug时看到的字符串是正常的,写到图片里就乱码了。
代码如下:
[code="java"]
/**
@param alpha 透明度
*/
public static void pressText2MultiImgs(String[] pressTexts, String targetImg, String outputImg,
Font font, Color color, int x, int widthMargin, int y, int heightMargin, float alpha) {
try {
File img = new File(targetImg);
Image src = ImageIO.read(img);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
g.setColor(color);
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int txtZoneWidth = width - widthMargin;//文字区域宽度,两边留间隙
int txtZoneHeight = height - heightMargin;//文字区域高度,上下留间隙
int lineNum = 0;//当前行数
// 处理多行字符
int fontSize = font.getSize();
for(String pressText : pressTexts){
List<String> strLines = getLineStr(pressText, fontSize, txtZoneWidth);
for(String str : strLines){
log.debug("行:" + str);//1
lineNum++;
g.drawString(str, x + (widthMargin / 2), fontSize * lineNum + (heightMargin / 2) + y);
}
}
g.dispose();
File imgOutput = new File(outputImg);
ImageIO.write((BufferedImage) image, "jpg", imgOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
[/code]
测试代码如下:
[code="java"]
@Test
public void pressText2MultiImgsTest2(){
String pinyin = "āáăàaēéĕèeīíĭìiōóŏòoūúŭùuǖǘǚǜü";
log.info(pinyin);
ImageUtils.pressText2MultiImgs(new String[]{pinyin}, "D:/temp/createImg/template.jpg", "D:/temp/createImg/out/out_3.jpg", new Font("宋体", 36, 16), Color.black, 8, 32, 8, 20, 1.0f);
}
[/code]
这一串字符串中 "āáăàaēéĕèeīíĭìiōóŏòoūúŭùuǖǘǚǜü"有几个是写不到图片上的,是否有解决办法 呢 :(
[quote]新的问题是能不能在图片上中英文混杂写入时用不同的字体?[/quote]这个应该是不行的,你看一下你的 pressText2MultiImgs() 方法里,用到这个 Font 的地方就明白了,你无法先使用一个Font 写一会,再换另外一个 Font 来写一会。我觉得唯一的方法是,你多试几个中文字体,看看能不能找到一个可以显示上面“āáăàaēéĕèeīíĭìiōóŏòoūúŭùuǖǘǚǜü”这些所有字符。
[quote]这一串字符串中 "āáăàaēéĕèeīíĭìiōóŏòoūúŭùuǖǘǚǜü"有几个是写不到图片上的[/quote]把你的结果图传上来看一下呢