如何从 UIImage 获取 URL?

How to get URL from UIImage?

我有一个 iOS 应用程序,用户可以通过两种方式获取照片:

  1. Select 来自照片库 (UIImagePickerController)

  2. 从定制相机中点击它

这是我的代码,用于单击来自自定义相机的图像(这是在名为 Camera 的自定义 class 中,它是 UIView 的子 class )

func clickPicture(completion:@escaping (UIImage) -> Void) {

    guard let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)  else { return }

    videoConnection.videoOrientation = .portrait
    stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in

        guard let buffer = sampleBuffer else { return }

        let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
        let dataProvider = CGDataProvider(data: imageData! as CFData)
        let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)

        let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)

        completion(image)


    })
}

以下是我点击 ViewController 中的图片的方法:

@IBAction func clickImage(_ sender: AnyObject) {
    cameraView.clickPicture { (image) in
        //use "image" variable
    }
}

稍后,我尝试使用 CloudKit 将此图片上传到用户的 iCloud 帐户。但是我收到一条错误消息,指出记录太大。然后我遇到了 ,它说要使用 CKAsset。但是,CKAsset 的唯一构造函数需要 URL.

有没有通用的方法可以从任何 UIImage 获得 URL?否则,如何从我使用自定义相机单击的图像中获取 URL(我看到其他 关于从 UIImagePickerController 中获取 url)?谢谢!

CKAsset 表示一些外部文件(图像、视频、二进制数据等)。这就是为什么它需要 URL 作为初始参数。

对于你的情况,我建议使用以下步骤将大图像上传到 CloudKit:

  1. 保存UIImage到本地存储(例如文档目录)。
  2. 使用本地存储中图像的路径初始化 CKAsset
  3. 将资产上传到云端。
  4. 上传完成后从本地存储中删除图像。

这是一些代码:

// Save image.
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let filePath = "\(path)/MyImageName.jpg"

UIImageJPEGRepresentation(image, 1)!.writeToFile(filePath, atomically: true)

let asset = CKAsset(fileURL: NSURL(fileURLWithPath: filePath)!)
// Upload asset here.

// Delete image.
do {
    try FileManager.default.removeItem(atPath: filePath)
} catch {
    print(error)
}