How to use 'compression_encode_buffer' in Swift?

1.1k views Asked by At

I am using the compression library of Swift to compress an image as NSData. This is the code:

var imageCompressed:NSData
compression_encode_buffer( imageCompressed ,800000 , imageSelected , size , NULL , COMPRESSION_LZMA )

I am getting the following error message:

Cannot convert value of type NSData to expected argument type UnsafeMutablePointer

2

There are 2 answers

5
matt On

I think what you want is something like this (imageSelected and imageCompressed are assumed to be Swift 3 Data objects):

imageSelected.withUnsafeBytes {(fromBytes: UnsafePointer<UInt8>) -> Void in
    imageCompressed.withUnsafeMutableBytes {(toBytes: UnsafeMutablePointer<UInt8>) -> Void in
        compression_encode_buffer(toBytes, toSize, fromBytes, fromSize, nil, COMPRESSION_LZMA)
    }
}
0
jvarela On

As Matt has said you cannot write to an NSData object, because it is immutable. I strongly recommend that you use Swift Standard Library Data type instead. Then you could call withUnsafeMutableBytes and do what you want inside its closure.