Skip to content

Instantly share code, notes, and snippets.

@brindy
Created March 11, 2019 11:57
Show Gist options
  • Save brindy/25bc6ca23050d2f0e6d09d5fe8d46825 to your computer and use it in GitHub Desktop.
Save brindy/25bc6ca23050d2f0e6d09d5fe8d46825 to your computer and use it in GitHub Desktop.
macOS command line program to convert HEIC images to JPGs
import Foundation
import Cocoa
guard CommandLine.arguments.count > 1 else {
fatalError("Usage: heic2jpg <folder>")
}
let folder = CommandLine.arguments[1]
guard let files = try? FileManager().contentsOfDirectory(atPath: folder) else {
fatalError("Unable to get files from \(folder)")
}
files.forEach { file in
guard file.hasSuffix(".HEIC") else {
return
}
let imageFile = "\(folder)/\(file)"
guard let image = NSImage(contentsOfFile: imageFile) else {
fatalError("Failed to read \(imageFile)")
}
guard let bits = image.representations.first as? NSBitmapImageRep else {
fatalError("Couldn't get image data for \(imageFile)")
}
guard let data = bits.representation(using: .jpeg, properties: [:]) else {
fatalError("Couldn't convert \(imageFile) to jpg")
}
let jpg = file.dropLast(4).appending("jpg")
let targetFile = "\(folder)/\(jpg)"
let targetFileUrl = URL(fileURLWithPath: targetFile)
print("Writing", targetFile)
try! data.write(to: targetFileUrl, options: [ .atomic])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment