Skip to content

Instantly share code, notes, and snippets.

@sinoru
Created April 28, 2018 04:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sinoru/36b26cdbfcbc0899ff309f6cad6c1831 to your computer and use it in GitHub Desktop.
Save sinoru/36b26cdbfcbc0899ff309f6cad6c1831 to your computer and use it in GitHub Desktop.
ConvertToHEIC
#!/usr/bin/env swift
//
// ConvertToHEIC.swift
// ConvertToHEIC
//
// Created by Sinoru on 2018. 4. 28..
//
import Foundation
import ImageIO
import AVFoundation
for argument in CommandLine.arguments.dropFirst() {
print("Converting \(argument).")
let sourceFileURL = URL(fileURLWithPath: argument)
guard let imageSource = CGImageSourceCreateWithURL(sourceFileURL as CFURL, nil) else {
print("Can't not load \(sourceFileURL). Skip")
continue
}
let imageProperties = CGImageSourceCopyProperties(imageSource, nil)
let imageCount = CGImageSourceGetCount(imageSource)
let destinationFileURL = sourceFileURL.deletingPathExtension().appendingPathExtension("heic")
guard let imageDestination = CGImageDestinationCreateWithURL(destinationFileURL as CFURL, AVFileType.heic as CFString, imageCount, nil) else {
print("Can't not write \(destinationFileURL). Skip")
continue
}
CGImageDestinationSetProperties(imageDestination, imageProperties)
for index in 0..<imageCount {
CGImageDestinationAddImageFromSource(imageDestination, imageSource, index, [kCGImageDestinationLossyCompressionQuality: 0.8] as CFDictionary)
}
guard CGImageDestinationFinalize(imageDestination) else {
print("Can't not finalize \(destinationFileURL). Skip")
continue
}
}
@magic-akari
Copy link

Thanks for sharing the code. It helps a lot.
For those who have not installed Xcode, I transpiled this swift code into JXA(JavaScript for Automation).
ConvertToHEIC.js

@aikinai
Copy link

aikinai commented Dec 18, 2018

Thank you both! This is a huge help so I can encode my digital camera photos as HEIC before importing to iCloud Photos and save a lot of space.

I cleaned up (and colorized) the output a bit (Swift, JavaScript) just for my own personal photo-management scripts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment