Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an NSImage to a JPEG file in Swift?

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

like image 237
henster Avatar asked Jan 25 '16 21:01

henster


1 Answers

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
}
like image 194
JAL Avatar answered Sep 20 '22 08:09

JAL