1. java生成驗證碼
1.1 使用谷歌的驗證碼包
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
1.2 生成驗證碼方法
/**
* 創建圖片
* @author heliming
* @date 2023/8/29-16:29
* @throws IOException
*/
public static void createImg() throws IOException {
Properties properties = new Properties();
// 是否有邊框
properties.put("kaptcha.border", "no");
// 設置文字顏色
properties.put("kaptcha.textproducer.font.color", "black");
// 字體大小,默認40
properties.setProperty("kaptcha.textproducer.font.size", "40");
// 字符長度,默認爲5
properties.setProperty("kaptcha.textproducer.char.length", "5");
// 字符間距 默認爲2
properties.setProperty("kaptcha.textproducer.char.space", "4");
// 干擾 顏色
properties.setProperty("kaptcha.noise.color", "black");
// 驗證碼圖片寬度 默認爲200
properties.setProperty("kaptcha.image.width", "160");
// 驗證碼圖片高度 默認爲40
properties.setProperty("kaptcha.image.height", "50");
// 圖片樣式
properties.setProperty("kaptcha.obscurificator.impl",
"com.google.code.kaptcha.impl.WaterRipple");
// 背景顏色漸變,開始顏色
properties.setProperty("kaptcha.background.clear.from", "white");
// 背景顏色漸變,結束顏色
properties.setProperty("kaptcha.background.clear.to", "white");
Config config = new Config(properties);
DefaultKaptcha defaultkaptcha = new DefaultKaptcha();
defaultkaptcha.setConfig(config);
BufferedImage image = defaultkaptcha.createImage("bupy");
ImageIO.write(image, "jpg", new File("F:\\demo1\\aa.jpg"));
}
public static void main(String[] args) throws TesseractException, IOException {
createImg();
}
1.3 生成後的驗證碼
2. python識別驗證碼
查看python版本,我用的是Python 3.11.4
python -V
查看pip版本,我用的是23.2.1
pip -V
2.1 安裝ddddocr
pip3 install ddddocr
2.2 有些時候需要升級pip
pip install --upgrade pip
2.3 執行ocrtest2.py腳本
import ddddocr
ocr = ddddocr.DdddOcr()
with open('F:/demo1/aa.jpg', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
print(res)
2.4 如果執行失敗 報錯,python 屬性錯誤:模塊“PIL.Image”沒有屬性“ANTIALIAS”
是Pillow10.0沒這個方法了,推薦改爲9.5版本
pip uninstall Pillow
pip install Pillow==9.5.0
執行python .\ocrtest2.py