Skip to content

Instantly share code, notes, and snippets.

@mczachurski
Created June 28, 2018 19:46
Show Gist options
  • Save mczachurski/d3bb634f527a016e8e7f657ee3048c49 to your computer and use it in GitHub Desktop.
Save mczachurski/d3bb634f527a016e8e7f657ee3048c49 to your computer and use it in GitHub Desktop.
import Foundation
import AppKit
import AVFoundation
extension NSImage {
@objc var CGImage: CGImage? {
get {
guard let imageData = self.tiffRepresentation else { return nil }
guard let sourceData = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
return CGImageSourceCreateImageAtIndex(sourceData, 0, nil)
}
}
}
let output = "wallpapers-new/output.heic"
let quality = 0.9
var imageData: Data? = nil
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let destinationData = NSMutableData()
if let destination = CGImageDestinationCreateWithData(destinationData, AVFileType.heic as CFString, 16, nil) {
let options = [kCGImageDestinationLossyCompressionQuality: quality]
for index in 1...16 {
let fileURL = dir.appendingPathComponent("wallpapers-new/\(index).png")
let orginalImage = NSImage(contentsOf: fileURL)
if let cgImage = orginalImage?.CGImage {
CGImageDestinationAddImage(destination, cgImage, options as CFDictionary)
}
}
CGImageDestinationFinalize(destination)
imageData = destinationData as Data
let outputURL = dir.appendingPathComponent(output)
try! imageData?.write(to: outputURL)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment