iOS 8 Core Image saving a section of an Image via Swift

落爺英雄遲暮 提交于 2019-12-06 02:10:40

问题


I'm using CoreImage Framework for detecting Business Card. When I detect a rectangle (CIDetectorTypeRectangle) I draw an overlay using this method:

    func drawOverlay(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {

    var overlay = CIImage(color: CIColor(red: 0, green: 0, blue: 1.0, alpha: 0.3))
    overlay = overlay.imageByCroppingToRect(image.extent())
    overlay = overlay.imageByApplyingFilter("CIPerspectiveTransformWithExtent",
      withInputParameters: [
        "inputExtent": CIVector(CGRect: image.extent()),
        "inputTopLeft": CIVector(CGPoint: topLeft),
        "inputTopRight": CIVector(CGPoint: topRight),
        "inputBottomLeft": CIVector(CGPoint: bottomLeft),
        "inputBottomRight": CIVector(CGPoint: bottomRight)
      ])
    return overlay.imageByCompositingOverImage(image)
  }

Now I need to take automatically a picture of the selected area and save it. Does anyone know how to do it? Thanks!


回答1:


I have found the solution!

func cropBusinessCardForPoints(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {

        var businessCard: CIImage
        businessCard = image.imageByApplyingFilter("CIPerspectiveTransformWithExtent",
            withInputParameters: [
                "inputExtent": CIVector(CGRect: image.extent()),
                "inputTopLeft": CIVector(CGPoint: topLeft),
                "inputTopRight": CIVector(CGPoint: topRight),
                "inputBottomLeft": CIVector(CGPoint: bottomLeft),
                "inputBottomRight": CIVector(CGPoint: bottomRight)
            ])
        businessCard = image.imageByCroppingToRect(businessCard.extent())

        return businessCard
    }

Usage:

//Variables
    var context: CIContext!
    var orientation: UIImageOrientation = UIImageOrientation.Right



override func viewDidLoad() {
        super.viewDidLoad()

        //Initialize the CIContext
        context = CIContext(options:nil)

        ...
}

When a rectangle is detected:

//...

let businessCardImage = cropBusinessCardForPoints(image, topLeft: feature.topLeft, topRight: feature.topRight, bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)

//Convert CIImage to CGImage
let cgimg = context.createCGImage(businessCardImage, fromRect: businessCardImage.extent())

//Convert CGImage to UIImage
let newImage = UIImage(CGImage: cgimg, scale:1, orientation: orientation)


来源:https://stackoverflow.com/questions/26526787/ios-8-core-image-saving-a-section-of-an-image-via-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!