Prechádzať zdrojové kódy

Fix inverted scan orientation so documents display top-to-bottom.

Correct Vision rectangle coordinates for perspective correction and flip scanner band data that arrives upside down.

Co-authored-by: Cursor <cursoragent@cursor.com>
AhtashamShahzad1 1 mesiac pred
rodič
commit
640d06db0c

+ 5 - 2
smart_printer/ScanFileView.swift

@@ -270,10 +270,13 @@ enum ScanDocumentProcessor {
 
     private static func perspectiveCorrectedImage(from cgImage: CGImage, observation: VNRectangleObservation) -> NSImage? {
         let ciImage = CIImage(cgImage: cgImage)
-        let size = ciImage.extent.size
+        let extent = ciImage.extent
 
         func convert(_ point: CGPoint) -> CGPoint {
-            CGPoint(x: point.x * size.width, y: (1 - point.y) * size.height)
+            CGPoint(
+                x: extent.origin.x + point.x * extent.width,
+                y: extent.origin.y + point.y * extent.height
+            )
         }
 
         guard let filter = CIFilter(name: "CIPerspectiveCorrection") else { return nil }

+ 24 - 1
smart_printer/ScannerService.swift

@@ -599,7 +599,7 @@ private extension ScannerService {
         let rep = NSBitmapImageRep(cgImage: cgImage)
         let image = NSImage(size: NSSize(width: bandData.fullImageWidth, height: bandData.dataNumRows))
         image.addRepresentation(rep)
-        return image
+        return verticallyFlipped(image)
     }
 
     func assembleImage(from bands: [ICScannerBandData]) -> NSImage? {
@@ -642,7 +642,30 @@ private extension ScannerService {
             let rep = NSBitmapImageRep(cgImage: cgImage)
             let image = NSImage(size: NSSize(width: width, height: height))
             image.addRepresentation(rep)
+            return verticallyFlipped(image)
+        }
+    }
+
+    func verticallyFlipped(_ image: NSImage) -> NSImage {
+        guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return image }
+        let width = cgImage.width
+        let height = cgImage.height
+        let colorSpace = cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB()
+        guard let context = CGContext(
+                  data: nil,
+                  width: width,
+                  height: height,
+                  bitsPerComponent: cgImage.bitsPerComponent,
+                  bytesPerRow: 0,
+                  space: colorSpace,
+                  bitmapInfo: cgImage.bitmapInfo.rawValue
+              ) else {
             return image
         }
+        context.translateBy(x: 0, y: CGFloat(height))
+        context.scaleBy(x: 1, y: -1)
+        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
+        guard let flipped = context.makeImage() else { return image }
+        return NSImage(cgImage: flipped, size: NSSize(width: width, height: height))
     }
 }