NSKeyedArchiver
是否适合将UIImage
转换为Data
?
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: UIImage(named: somePath), requiringSecureCoding: true)
...
} catch {
print(error)
}
或者是矫kill过正,使用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
并将UIImage
的imageOrientation
转换为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: imageOrientation.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.Orientation { var cgImageOrientation: CGImagePropertyOrientation { .init(self) } }
无损压缩的用法:
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
}