我正在开发一个带有xcode 9和iPhone SE的iOS应用程序。
我得到一张大照片,这是一张 19MB JPEG
图片,格式来自 iPhone 相册NSData
格式。
然后我需要修复此照片方向,因此我必须将此照片从NSData
转换为UIImage
。然后我需要将此UIImage
还原为 NSData(less than 20MB)
.
当我尝试使用UIImageJPEGRepresentation()
时,设备内存飙升至1.2G并崩溃。
当我尝试用户UIImagePNGRepresentation()
时,对象NSData
结果大于20MB。
我不知道该怎么做。谁能帮忙?谢谢!
我想未压缩的19MBjpeg将占用大量空间。我对您的设备内存增加这么多并不感到惊讶。Jpeg 在其属性数据中存储方向属性。为了避免必须解压缩 jpeg,您可以只编辑属性数据来固定方向。
如果图像数据是 jpeg 数据,则可以按如下方式编辑属性。这使用 Swift Data 对象,但您可以相当轻松地在 NSData 和数据之间跳转
。// create an imagesourceref
if let source = CGImageSourceCreateWithData(imageData as CFData, nil) {
// get image properties
var properties : NSMutableDictionary = [:]
if let sourceProperties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) {
properties = NSMutableDictionary(sourceProperties)
}
// set image orientation
properties[kCGImagePropertyOrientation] = 4
if let uti = CGImageSourceGetType(source) {
// create a new data object and write the new image into it
let destinationData = NSMutableData()
if let destination = CGImageDestinationCreateWithData(destinationData, uti, 1, nil) {
// add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
CGImageDestinationAddImageFromSource(destination, source, 0, properties)
if CGImageDestinationFinalize(destination) == false {
return nil
}
return destinationData as Data
}
}
}
方向值如下
纵向 = 6
纵向倒置 = 8
landscape_volumebuttons_up = 3
landscape_powerbutton_up = 1