我需要做同样的事情——将iOS中的UIImage保存到可用的Windows .bmp文件中。我实际上在Adafruit PyPortal IoT设备上使用了它,而不是在Windows机器上,但下面的技巧运行良好。将数据保存到Firebase存储中,并能够在PyPortal中使用它。
我在这里找到了一个有用的扩展:
如何在Swift中将UIImage转换为NSData并转换回UIImage?
我使用了这个扩展:
// 注意,您需要导入MobileCoreServices才能识别k值
import MobileCoreServices
extension UIImage {
func toJpegData (compressionQuality: CGFloat, hasAlpha: Bool = true, orientation: Int = 6) -> Data? {
guard cgImage != nil else { return nil }
let options: NSDictionary = [
kCGImagePropertyOrientation: orientation,
kCGImagePropertyHasAlpha: hasAlpha,
kCGImageDestinationLossyCompressionQuality: compressionQuality
]
return toData(options: options, type: .jpeg)
}
func toData (options: NSDictionary, type: ImageType) -> Data? {
guard cgImage != nil else { return nil }
return toData(options: options, type: type.value)
}
func toData (options: NSDictionary, type: CFString) -> Data? {
guard let cgImage = cgImage else { return nil }
return autoreleasepool { () -> Data? in
let data = NSMutableData()
guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, type, 1, nil) else { return nil }
CGImageDestinationAddImage(imageDestination, cgImage, options)
CGImageDestinationFinalize(imageDestination)
return data as Data
}
}
enum ImageType {
case image
case jpeg
case jpeg2000
case tiff
case pict
case gif
case png
case quickTimeImage
case appleICNS
case bmp
case ico
case rawImage
case scalableVectorGraphics
case livePhoto
var value: CFString {
switch self {
case .image: return kUTTypeImage
case .jpeg: return kUTTypeJPEG
case .jpeg2000: return kUTTypeJPEG2000
case .tiff: return kUTTypeTIFF
case .pict: return kUTTypePICT
case .gif: return kUTTypeGIF
case .png: return kUTTypePNG
case .quickTimeImage: return kUTTypeQuickTimeImage
case .appleICNS: return kUTTypeAppleICNS
case .bmp: return kUTTypeBMP
case .ico: return kUTTypeICO
case .rawImage: return kUTTypeRawImage
case .scalableVectorGraphics: return kUTTypeScalableVectorGraphics
case .livePhoto: return kUTTypeLivePhoto
}
}
}
}
我在代码中这样调用:
(我正在转换的图像是一个名为backgroundImage
的UIImage
属性,它是包含下面代码的类的一个属性)。
let options: NSDictionary = [:]
let convertToBmp = self.backgroundImage.toData(options: options, type: .bmp)
guard let bmpData = convertToBmp else {
print(" ERROR: could not convert image to a bitmap bmpData var.")
return
}
干杯!