0

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

我得到一张大照片,它是一张 19MB 的JPEG图片,NSData格式来自 iPhone 相册。

然后我需要修复这张照片的方向,所以我必须把这张照片NSDataUIImage. 然后我需要将其还原UIImageNSData(less than 20MB).

当我尝试使用时UIImageJPEGRepresentation(),设备内存猛增至 1.2G 并崩溃。

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

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

4

1 回答 1

1

我想一个未压缩的 19MB jpeg 会占用大量空间。我对您的设备内存增加如此之多并不感到惊讶。Jpeg 在其属性数据中存储了一个方向属性。为避免必须解压缩 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
        }
    }
}

方向值如下

肖像 = 6
Portraitupsidedown = 8
Landscape_volumebuttons_up = 3
Landscape_powerbutton_up = 1

于 2017-11-16T11:38:41.623 回答