1.后端接口代码,要自己去申请百度key
import com.baidu.aip.ocr.AipOcr;
import com.medical.dto.RespResult;
import com.medical.service.StreamQwen;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
@RestController
public class BaiduOCRController {
// 设置百度AI的相关信息
public static final String APP_ID = "61762";
public static final String API_KEY = "x1z09u4by2nirxNDoto4";
public static final String SECRET_KEY = "pYcQ2Sp0Izo1eiupeO2aTZIkMH";
@Resource
private StreamQwen streamQwen;
@PostMapping("/uploadAndRecognize")
public RespResult uploadAndRecognize(@RequestParam("file") MultipartFile file) {
try {
// 保存上传的文件到临时目录
File tempFile = File.createTempFile("temp", null);
file.transferTo(tempFile);
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 设置请求参数
HashMap<String, String> options = new HashMap<>();
options.put("language_type", "CHN_ENG"); // 识别语言类型,默认为CHN_ENG(中英文混合)
options.put("detect_direction", "true"); // 是否检测图像朝向,默认不检测
// 调用接口进行文字识别
JSONObject res = client.basicGeneral(tempFile.getAbsolutePath(), options);
System.out.println(res);
JSONArray wordsResult = res.getJSONArray("words_result");
System.out.println("wordsResult: " + wordsResult);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < wordsResult.length(); i++) {
JSONObject wordObject = wordsResult.getJSONObject(i);
String words = wordObject.getString("words");
stringBuilder.append(words);
}
// 调用通义千问的api接口
return RespResult.success(streamQwen.testStreamCall(stringBuilder.toString()));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("图片的文字识别异常");
}
}
}
具体流程: 先把图片上传到一个临时目录,然后调用API拿到图片进行文字识别,最后把文字放进String Builder进行拼接,我们就可以使用了