Files
swiftGrammar/AIGrammar/GrammarSubView/CameraView.swift
2024-08-12 10:49:20 +08:00

92 lines
3.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CameraView.swift
// AIGrammar
//
// Created by oscar on 2024/4/3.
//
import SwiftUI
import UIKit
import Vision
func performOCR(on uiImage: UIImage, completion: @escaping (String) -> Void) {
guard let cgImage = uiImage.cgImage else { return }
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let request = VNRecognizeTextRequest { (request, error) in
guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
let recognizedStrings = observations.compactMap { $0.topCandidates(1).first?.string }
completion(recognizedStrings.joined(separator: "\n"))
}
request.recognitionLanguages = ["en-US", "zh-Hans"] //
request.usesLanguageCorrection = true
do {
try handler.perform([request])
} catch {
print("OCR失败: \(error)")
}
}
struct CameraView: UIViewControllerRepresentable {
@Binding var textInput: String
@Environment(\.presentationMode) var presentationMode
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = .camera
picker.allowsEditing = true //
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var parent: CameraView
init(_ parent: CameraView) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//
if let editedImage = info[.editedImage] as? UIImage {
// 使OCR
performOCR(on: editedImage) { recognizedText in
//
self.parent.textInput = recognizedText
self.parent.presentationMode.wrappedValue.dismiss()
}
} else if let originalImage = info[.originalImage] as? UIImage {
// 退使
performOCR(on: originalImage) { recognizedText in
self.parent.textInput = recognizedText
self.parent.presentationMode.wrappedValue.dismiss()
}
} else {
//
self.parent.presentationMode.wrappedValue.dismiss()
}
}
func imagePickerController2(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
// OCR
performOCR(on: uiImage) { recognizedText in
//
self.parent.textInput = recognizedText
}
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}