Home > Net >  UIImage to URL with swift
UIImage to URL with swift

Time:03-24

I have an UIImage generated from a CanvasView. I want to use the featureprintObservationForImage feature on it. However it seems to take a URL and I am trying to provide a UIImage, how can I get around this?

Here is my code:

//getting image
UIGraphicsBeginImageContextWithOptions(theCanvasView.bounds.size, false, UIScreen.main.scale)
        theCanvasView.drawHierarchy(in: theCanvasView.bounds, afterScreenUpdates: true)
        
        let image2 = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

//setting up observation for image
let drawing = featureprintObservationForImage(atURL: Bundle.main.url(image2)!)

I am getting the error on the last line that says:

Cannot convert value of type 'UIImage?' to expected argument type 'String'

Any ideas?

CodePudding user response:

Assuming that you need to get a VNFeaturePrintObservation instance, you could request an image instead of a URL by using the VNImageRequestHandler.

Assuming that featureprintObservationForImage method is (or looks something like this):

func featureprintObservationForImage(atURL url: URL) -> VNFeaturePrintObservation? {
    let requestHandler = VNImageRequestHandler(url: url, options: [:])
    let request = VNGenerateImageFeaturePrintRequest()
    do {
        try requestHandler.perform([request])
        return request.results?.first as? VNFeaturePrintObservation
    } catch {
        print("Vision error: \(error)")
        return nil
    }
}

You could have a different version as:

func featureprintObservationForImage(_ image: CIImage?) -> VNFeaturePrintObservation? {
    guard let ciImage = image else {
        return nil
    }
    let requestHandler = VNImageRequestHandler(ciImage: ciImage, options: [:])
    let request = VNGenerateImageFeaturePrintRequest()
    do {
      try requestHandler.perform([request])
      return request.results?.first as? VNFeaturePrintObservation
    } catch {
      print("Vision error: \(error)")
      return nil
    }
  }

The differences in the second one are:

  • The signature of the method, takes an optional CIImage instead of a URL.

  • The initializer of the requestHandler.

Therefore:

let drawing = featureprintObservationForImage(image2?.ciImage)
  • Related