不要使用NSKeyedArchiver将您的图像转换为数据。选择图像格式(HEIC,PNG,JPEG等)并获取其数据表示形式。仅在保存用于UI的图像时才应使用PNG。大多数情况下,jpeg是首选。如果设备支持HEIC,则可以考虑其图像质量和减小的数据大小。
如果您需要检查用户设备是否支持HEIC类型,则可以按以下步骤操作:
var isHeicSupported: Bool {
(CGImageDestinationCopyTypeIdentifiers() as! [String]).contains("public.heic")
}
如果您需要将图像转换为HEIC格式,则需要从UIImage
获取CGImage
并将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: 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
}
UIImage
或使用具有属性的结构体包装图像,那么推荐的数据序列化是什么? - lurning too koad