【问题标题】:ios UIImageJPEGRepresentation() with large image crashios UIImageJPEGRepresentation() 与大图像崩溃
【发布时间】:2017-11-16 08:47:45
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: ios memory crash uiimage uiimagejpegrepresentation


    【解决方案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

    【讨论】:

    • 你的答案适合 png 数据吗?
    • 应该是,虽然我没测试过
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多