Search code examples
iosswifttiffcgimage

Unable to compress tiff file in swift


My app has a requirement to capture a snapshot of a paper document using the iPad camera and pass it to a REST API in Tiff Format.

I have tried to capture an image using "UIImagePickerController" and convert it to Tiff format using "kUTTypeTIFF" in CGImageDestinationRef. It produces an uncompressed image which is around 20 to 30 MB in ipad pro12.9.

Now I am trying to compress the image using various formats, but I am confused because there are no guides found in swift tiff compression.

Lang: Swift

Code snippet for taking photo,

let chosenImage = info[UIImagePickerControllerOriginalImage] as! CGImage //2

let imgData = convertToTiffUsingUIImage(imgUI: info[UIImagePickerControllerOriginalImage] as! UIImage)

//Pass to REST
imageUploadRequest(imgData, uploadUrl: NSURL(string: "http://localhost:8080/user/service.jsp")!, param: ["userName": "xyz"])

self.dismissViewControllerAnimated(true, completion: nil);

Convert to tiff image

let key = kCGImagePropertyTIFFCompression
let value = 5

var keys = [ unsafeAddressOf(key) ]
var values = [ unsafeAddressOf(value) ]

var keyCallBacks = kCFTypeDictionaryKeyCallBacks
var valueCallBacks = kCFTypeDictionaryValueCallBacks

let cfDictionary = CFDictionaryCreate(kCFAllocatorDefault, &keys, &values, 1, &keyCallBacks, &valueCallBacks) 

let data = NSMutableData()

let dr: CGImageDestinationRef = CGImageDestinationCreateWithData(data, kUTTypeTIFF, 1, cfDictionary)!

CGImageDestinationAddImage(dr, imgUI.CGImage!, nil);

CGImageDestinationFinalize(dr);

print(data.length);

if data.length > 0 {
    UIImageWriteToSavedPhotosAlbum(UIImage(data:data)!, nil, nil, nil);
}

But this doesn't result in a compressed Image.

Can anyone help me to understand the Tiff file compression in swift ?


Solution

  • You should not be passing photos around as TIFF. A photo wants to be a JPG, and that is the format you should be using. To put it another way, the compressed version of a photo is a JPG. Don't use TIFF as an intermediary.

    (A small number of recent devices support RAW, but you can't count on that.)