ios UIImageJPEGRepresentation()与大图像崩溃

时间:2017-11-16 08:47:46

标签: ios memory crash uiimage uiimagejpegrepresentation

我正在使用xcode 9和iPhone SE开发iOS应用程序。

我从iPhone相册中收到一张19MB JPEGNSData张照片的大照片。

然后我需要修复此照片方向,因此我必须将此照片从NSData转换为UIImage。 然后我需要将此UIImage还原为NSData(less than 20MB)

当我尝试使用UIImageJPEGRepresentation()并且设备内存高达1.2G并崩溃时。

当我尝试使用UIImagePNGRepresentation()时,结果NSData对象大于20MB。

我不知道该怎么做。 有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我想一个19MB的未压缩的jpeg会占用大量的空间。我对你的设备内存增长如此惊讶并不感到惊讶。 Jpegs在其属性数据中存储方向属性。为避免必须解压缩jpeg,您只需编辑属性数据即可修复方向。

如果imageData是您的jpeg数据,您可以按如下方式编辑属性。这使用了Swift Data对象,但您可以非常轻松地在NSData和Data之间跳转

// 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
        }
    }
}

方向值如下

portrait = 6
portraitupsidedown = 8
landscape_volumebuttons_up = 3
landscape_powerbutton_up = 1