我正在用xcode 9和iPhone SE开发一个iPhone应用程序。
我得到一张大照片,这是一张19 an的JPEG
图片,带有NSData
格式,来自iPhone相册。
然后我需要修复这个照片方向,所以我必须将这张照片从NSData
转换成UIImage
。然后,我需要将这个UIImage
恢复为NSData(less than 20MB)
。
当我尝试使用UIImageJPEGRepresentation()
和设备时,内存高达1.2G并崩溃。
当我尝试使用UIImagePNGRepresentation()
时,结果NSData
对象大于20 is。
我不知道该怎么做。有人能帮忙吗?谢谢!
发布于 2017-11-16 11:38:41
我想,一个19 of的jpeg未压缩将占用巨大的空间。我不奇怪你的设备内存会增加这么多。Jpegs在其属性数据中存储一个定向属性。为了避免不得不解压缩jpeg,您可以只编辑属性数据来修复方向。
如果imageData是jpeg数据,您可以按如下方式编辑属性。这使用Swift数据对象,但是您可以很容易地在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
https://stackoverflow.com/questions/47325187
复制相似问题