I can't see a direct way to read the bytes in the tiff. I've tried:
func printTiffBytes(url:URL) {
if let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) {
let width = image.width
let height = image.height
let bitsPerComponent = image.bitsPerComponent
let bytesPerRow = image.bytesPerRow
let totalBytes = height * bytesPerRow
let colorSpace = CGColorSpaceCreateDeviceRGB()
// let colorSpace = CGColorSpace(name: CGColorSpace.linearSRGB)!
//let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue) // Error! unsupported parameter combination
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let data = UnsafeMutableRawPointer.allocate(byteCount: totalBytes, alignment: MemoryLayout<UInt8>.alignment)
defer { data.deallocate() }
if let context = CGContext(data: data,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue) {
context.draw(image, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height)))
let buffer = data.assumingMemoryBound(to: UInt8.self)
for i in 0..<totalBytes {
print(buffer[i])
}
}
}
}
but I cannot get it to wrk with CGImageAlphaInfo.last so I'm not all that confident this is really what's in the tiff. But for the test pixel [120, 145, 195, 170] I get [155,116
,97,170] (I guess RGB order is reversed?)