NSKeyedArchiver是否适合将UIImage转换为Data

do {
    let data = try NSKeyedArchiver.archivedData(withRootObject: UIImage(named: somePath), requiringSecureCoding: true)
    ...
} catch {
    print(error)
}

还是过度矫and,使用pngData()更合适?
let image = UIImage(named: somePath)
let data = image?.pngData()

以及如何从UIImage转换为HEIF/HEIC Data

目的是将镜像保存到设备的文件系统中。

最佳答案

否。切勿使用NSKeyedArchiver将图像转换为数据。选择图像格式(HEIC,PNG,JPEG等)并获取其数据表示形式。保存图像以在UI中使用时,仅应使用PNG。大多数情况下,jpeg是首选。如果设备支持HEIC,则可以选择考虑图像质量和减小的数据大小。
如果需要检查用户设备是否支持HEIC类型,可以按照以下步骤进行操作:

var isHeicSupported: Bool {
    (CGImageDestinationCopyTypeIdentifiers() as! [String]).contains("public.heic")
}
如果需要将图像转换为HEIC,则需要从CGImage获取UIImage,并将UIImageimageOrientation转换为CGImagePropertyOrientation,以在创建其数据表示形式时保留方向:
extension UIImage {
    var heic: Data? { heic() }
    func heic(compressionQuality: CGFloat = 1) -> Data? {
        guard
            let mutableData = CFDataCreateMutable(nil, 0),
            let destination = CGImageDestinationCreateWithData(mutableData, "public.heic" as CFString, 1, nil),
            let cgImage = cgImage
        else { return nil }
        CGImageDestinationAddImage(destination, cgImage, [kCGImageDestinationLossyCompressionQuality: compressionQuality, kCGImagePropertyOrientation: cgImageOrientation.rawValue] as CFDictionary)
        guard CGImageDestinationFinalize(destination) else { return nil }
        return mutableData as Data
    }
}
extension CGImagePropertyOrientation {
    init(_ uiOrientation: UIImage.Orientation) {
        switch uiOrientation {
            case .up: self = .up
            case .upMirrored: self = .upMirrored
            case .down: self = .down
            case .downMirrored: self = .downMirrored
            case .left: self = .left
            case .leftMirrored: self = .leftMirrored
            case .right: self = .right
            case .rightMirrored: self = .rightMirrored
        @unknown default:
            fatalError()
        }
    }
}
extension UIImage {
    var cgImageOrientation: CGImagePropertyOrientation { .init(imageOrientation) }
}

无损压缩的用法:
if isHeicSupported, let heicData = image.heic {
    // write your heic image data to disk
}
或为图像添加压缩:
if isHeicSupported, let heicData = image.heic(compressionQuality: 0.75) {
    // write your compressed heic image data to disk
}

10-08 15:40