Skip to content

Instantly share code, notes, and snippets.

@songxing10000
Created March 8, 2024 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save songxing10000/a22924fa5a2175a56551c1870b8fbd7a to your computer and use it in GitHub Desktop.
Save songxing10000/a22924fa5a2175a56551c1870b8fbd7a to your computer and use it in GitHub Desktop.
AlibabacloudOcrApi20210707图片转文字
//
// Img2textVC.swift
// AudioText
//
// Created by dfpo on 2024/3/8.
// 图片转文字
import UIKit
import TOCropViewController
import AlibabacloudOpenApi
import AlibabacloudOcrApi20210707
import Tea
import TeaUtils
import SnapKit
class Img2textVC: SXCusNavBarVC {
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("image_to_text", comment: "")
view.addSubview(m_selectPicturesFromTheAlbumBtn)
m_selectPicturesFromTheAlbumBtn.snp.makeConstraints { (make) in
make.top.equalTo(m_navBar.snp.bottom).offset(30)
make.centerX.equalToSuperview()
}
view.addSubview(m_SelectedImagesImgV)
m_SelectedImagesImgV.snp.makeConstraints { (make) in
make.top.equalTo(m_selectPicturesFromTheAlbumBtn.snp.bottom).offset(20)
make.left.right.equalToSuperview().inset(20)
make.height.equalTo(m_SelectedImagesImgV.snp.width)
}
view.addSubview(m_RecognitionResultLabel)
m_RecognitionResultLabel.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.top.equalTo(m_SelectedImagesImgV.snp.bottom).offset(20)
}
}
// MARK: 从相册选择图片 按钮事件
/// 从相册选择图片 按钮事件
@objc
private func clickSelectPicturesFromTheAlbumBtn(_ btn: UIButton){
selectPhotoFromAlbum()
}
private func selectPhotoFromAlbum() {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
}
private func presentEditImgVCByImg(_ selectedImage: UIImage) {
let cropViewController = TOCropViewController(image: selectedImage)
cropViewController.delegate = self
present(cropViewController, animated: true, completion: nil)
}
private func makeConfig() ->AlibabacloudOpenApi.Config {
let config = AlibabacloudOpenApi.Config([
"accessKeyId": APP_ALI_KEY_ID,
"accessKeySecret": APP_ALI_SECRET
])
config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com"
return config
}
/// 图片转文字测试
private func recognizingTextFromImg(_ img: UIImage) async {
guard let imgData = img.pngData() else {
debugPrint("获取图片二进制出错")
return
}
do {
let request = AlibabacloudOcrApi20210707.RecognizeGeneralRequest([:])
request.body = InputStream(data: imgData)
let client = try AlibabacloudOcrApi20210707.Client(makeConfig())
let response = try await client.recognizeGeneralWithOptions(request , TeaUtils.RuntimeOptions([:]) )
showContentFromResponse(response)
}
catch {
if error is Tea.TeaError, let e = error as? Tea.ReuqestError {
if let code = e.code {
debugPrint("图片转文字失败code: \(code)")
}
if let msg = e.message {
debugPrint("图片转文字失败msg: \(msg)")
}
}
}
}
private func showContentFromResponse(_ response: RecognizeGeneralResponse) {
if let resStr = response.body?.data,
let resData = resStr.data(using: .utf8) {
do {
let resObj = try JSONDecoder().decode(Img2TextRes.self, from: resData)
if let content = resObj.content {
m_RecognitionResultLabel.text = "识别结果:\n\(content)"
}
} catch {
debugPrint("解码失败: \(error)")
}
}
}
/// 从相册选择图片
lazy var m_selectPicturesFromTheAlbumBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("从相册选择图片", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
btn.setTitleColor(.color_3878F5, for: .normal)
btn.layer.borderColor = UIColor.color_3878F5.cgColor
btn.layer.borderWidth = 1
btn.translatesAutoresizingMaskIntoConstraints = false
btn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)
btn.addTarget(self, action: #selector(clickSelectPicturesFromTheAlbumBtn), for: .touchUpInside)
btn.layer.cornerRadius = btn.intrinsicContentSize.height * 0.5
return btn
}()
/// 选择的图片
lazy var m_SelectedImagesImgV: UIImageView = {
let imgV = UIImageView()
imgV.translatesAutoresizingMaskIntoConstraints = false
return imgV
}()
/// 识别结果
lazy var m_RecognitionResultLabel: UILabel = {
let lab = UILabel()
lab.text = "识别结果..."
lab.textColor = UIColor.black
lab.font = UIFont.systemFont(ofSize: 14.0)
lab.numberOfLines = 0
lab.textAlignment = .center
lab.translatesAutoresizingMaskIntoConstraints = false
return lab
}()
}
extension Img2textVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
if let selectedImage = info[.originalImage] as? UIImage {
presentEditImgVCByImg(selectedImage)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
extension Img2textVC: TOCropViewControllerDelegate {
func cropViewController(_ cropViewController: TOCropViewController, didCropTo image: UIImage, with cropRect: CGRect, angle: Int) {
m_SelectedImagesImgV.image = image
Task{
await recognizingTextFromImg(image)
}
cropViewController.dismiss(animated: true, completion: nil)
}
}
@songxing10000
Copy link
Author

AlibabacloudOpenApi库中,文件Client的695行:
#warning("源码修改")
_request.body = request.stream //原代码Tea.TeaCore.toReadable(tmp as! [UInt8])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment