不,永远不要使用 NSKeyedArchiver 将您的图像转换为数据。选择一种图像格式(HEIC、PNG、JPEG 等)并获取其数据表示。在保存要在 UI 中使用的图像时,您应该只使用 PNG。大多数情况下,jpeg 是首选。如果设备支持 HEIC,则考虑到图像质量和减小的数据大小,这是一个选项。
如果您需要检查用户设备是否支持 HEIC 类型,您可以执行以下操作:
var isHeicSupported: Bool {
(CGImageDestinationCopyTypeIdentifiers() as! [String]).contains("public.heic")
}
如果您需要将图像转换为 HEIC,则需要CGImage
从您的图像中获取 aUIImage
并将UIImage
's转换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: 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
}