中文驗(yàn)證碼圖片亂碼
如果生成的含有中文驗(yàn)證碼的圖片亂碼需要按以下方式修改嗎?還是只要添加幾行代碼修改一下就行?
確認(rèn)%JavaHome%/jre/lib/fonts目錄下存在zysong.ttf,如果不存在,可以將windows下的C:\WINDOWS\Fonts\simsun.ttc復(fù)制到此目錄,然后改名為zysong.ttf。
2.在%JavaHome%/jre/lib/fonts目錄下執(zhí)行"ttmkfdir -o fonts.dir"命令,重新生成fonts.dir文件,如沒有此命令,請執(zhí)行:sudo apt-get install ttmkfdir。
3.確認(rèn)/usr/share/fonts/zh_CN/TrueType目錄存在,如果不存在則mkdir創(chuàng)建
4.確認(rèn)/usr/share/fonts/zh_CN/TrueType目錄下存在zysong.ttf
5.在%JavaHome%/jre/lib目錄下,執(zhí)行 cp fontconfig.RedHat.3.properties.src fontconfig.properties
6.重新啟動tomcat其實(shí)圖片上應(yīng)為“網(wǎng)驗(yàn)”二字,但是亂碼只看到了“網(wǎng)”字
這部分源代碼(下載此課程的源代碼):
package com.imooc.kaptcha;
import java.util.Random;
public class ChineseText extends Configurable implements TextProducer {
public String getText() {
int length = getConfig().getTextProducerCharLength();
//char[] charS = getConfig().getTextProducerCharString();
String[] s = new String[]{"慕","課","網(wǎng)","教","程","驗(yàn)","證","碼","實(shí)","例"};
Random rand = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length; i++){
int ind = rand.nextInt(s.length);
sb.append(s[ind]);
}
return sb.toString();
}
/**
* 中文實(shí)例
* @return
*/
public String getText1() {
int length = getConfig().getTextProducerCharLength();
String finalWord = "", firstWord = "";
int tempInt = 0;
String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f" };
Random rand = new Random();
for (int i = 0; i < length; i++) {
switch (rand.nextInt(array.length)) {
case 1:
tempInt = rand.nextInt(26) + 65;
firstWord = String.valueOf((char) tempInt);
break;
case 2:
int r1,
r2,
r3,
r4;
String strH,
strL;// high&low
r1 = rand.nextInt(3) + 11; // 前閉后開[11,14)
if (r1 == 13) {
r2 = rand.nextInt(7);
} else {
r2 = rand.nextInt(16);
}
r3 = rand.nextInt(6) + 10;
if (r3 == 10) {
r4 = rand.nextInt(15) + 1;
} else if (r3 == 15) {
r4 = rand.nextInt(15);
} else {
r4 = rand.nextInt(16);
}
strH = array[r1] + array[r2];
strL = array[r3] + array[r4];
byte[] bytes = new byte[2];
bytes[0] = (byte) (Integer.parseInt(strH, 16));
bytes[1] = (byte) (Integer.parseInt(strL, 16));
firstWord = new String(bytes);
break;
default:
tempInt = rand.nextInt(10) + 48;
firstWord = String.valueOf((char) tempInt);
break;
}
finalWord += firstWord;
}
return finalWord;
}
}