A Swift question. Not an Obj-C question. Please don't mark it as duplicate
I am trying to write a class that generates a JPEG thumbnail on OS X. I hope I have something sensible that forms the scaled down NSImage but I'm struggling to write a JPEG file to disk.
class ImageThumbnail {
let size = CGSize(width: 128, height: 128)
var originalPath = ""
init(originalPath: String){
self.originalPath = originalPath
}
func generateThumbnail() {
let url = NSURL(fileURLWithPath: originalPath)
if let imageSource = CGImageSourceCreateWithURL(url, nil) {
let options: [NSString: NSObject] = [
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) / 2.0,
kCGImageSourceCreateThumbnailFromImageAlways: true
]
let cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options)
let scaledImage = cgImage.flatMap { NSImage(CGImage: $0, size: size) }
// How do I write scaledImage to a JPEG file?
}
}
}
Example usage: ImageThumbail(originalPath: "/path/to/original").generateThumbnail()
First you need to get a bitmap representation of the image, get a JPEG representation of that image (or whatever format you want), and then write the binary data to a file:
if let bits = scaledImage?.representations.first as? NSBitmapImageRep {
let data = bits.representationUsingType(.NSJPEGFileType, properties: [:])
data?.writeToFile("/path/myImage.jpg", atomically: false)
}
NSBitmapImageFileType
gives you a choice of representations:
public enum NSBitmapImageFileType : UInt {
case NSTIFFFileType
case NSBMPFileType
case NSGIFFileType
case NSJPEGFileType
case NSPNGFileType
case NSJPEG2000FileType
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With