ios UIImageJPEGRepresentation() 大图像崩溃

标签 ios memory crash uiimage uiimagejpegrepresentation

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

我从 iPhone 相册中获取了一张大照片,该照片是 19MB 的 JPEG 图片,格式为 NSData

然后我需要修复这张照片的方向,因此我必须将这张照片从 NSData 转换为 UIImage。 然后我需要将此 UIImage 恢复为 NSData(小于 20MB)

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

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

我不知道该怎么做。 谁能帮忙?谢谢!

最佳答案

我想象未压缩的 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
人像颠倒 = 8
landscape_volumebuttons_up = 3
landscape_powerbutton_up = 1

关于ios UIImageJPEGRepresentation() 大图像崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47325187/

相关文章:

javascript - 如何重定向到phonegap iphone中的本地html页面

java - 获取其他jvm的内存使用详情

debugging - 如何调试 IE8 崩溃?

ios - 我如何向 CoreData 指示对象已更改?

ios - 奇怪的 UIScrollView 行为

ios - iOS 应用程序中的条形图

memory - Unix : sharing already-mapped memory between processes

java - 存储方法(堆栈/堆)中的局部最终变量在哪里?

c++ - std vector 中的 push_back() 崩溃

ios - NSRegularExpression 崩溃