无法在swift中压缩tiff文件

时间:2017-02-01 15:34:24

标签: ios swift tiff cgimage

我的应用程序需要使用iPad相机捕获纸质文档的快照,并将其传递给Tiff格式的REST API。

我尝试使用" UIImagePickerController"捕获图像。并使用" kUTTypeTIFF"将其转换为Tiff格式;在CGImageDestinationRef中。它产生的未压缩图像在ipad pro12.9中大约为20到30 MB。

现在我正在尝试使用各种格式压缩图像,但我很困惑,因为在快速tiff压缩中没有找到指南。

郎:斯威夫特

拍照的代码段,

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);

转换为tiff图像

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);
}

但这并不会导致压缩的图像。

任何人都可以帮我理解swift中的Tiff文件压缩吗?

2 个答案:

答案 0 :(得分:1)

你不应该把照片作为TIFF传递。照片想成为JPG,这是您应该使用的格式。换句话说,照片的压缩版本是 JPG。不要使用TIFF作为中间人。

(少数最近的设备支持RAW,但你不能指望它。)

答案 1 :(得分:1)

这是我在this回答中转换代码的粗略尝试。

import Cocoa
import ImageIO
import CoreServices

func writeCCITTTiffWithCGImageURL(im: CGImage, url: CFURL)
{
   guard let colorSpace = CGColorSpace(name: CGColorSpace.genericGrayGamma2_2) else { print("Color space deosn't exist"); return }
   guard let bitmapCtx = CGContext(data: nil, width: im.width, height: im.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue) else { print("Could not make bitmapContext"); return }

   bitmapCtx.draw(im, in: CGRect(x: 0, y: 0, width: im.width, height: im.height))
   guard let grayScaleImage: CGImage = bitmapCtx.makeImage()
   else { print("Could not make grayScale Image"); return }

   let tiffOptions: Dictionary<String, Int> = [String(kCGImagePropertyTIFFCompression) : 4]
   let options: NSDictionary = [String(kCGImagePropertyTIFFDictionary) : tiffOptions, kCGImagePropertyDepth : 1]

   guard let imageDestination = CGImageDestinationCreateWithURL(url, kUTTypeTIFF, 1, nil) else { print("Could not make imageDestination"); return }
   CGImageDestinationAddImage(imageDestination, grayScaleImage, options)
   CGImageDestinationFinalize(imageDestination)
}