Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created June 1, 2024 14:58
Show Gist options
  • Save JoshuaSullivan/b08fa021ebdff062a2ad3ddd59ae42d4 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/b08fa021ebdff062a2ad3ddd59ae42d4 to your computer and use it in GitHub Desktop.
Function to write image directly to URL
import Foundation
import UIKit
import CoreImage
import Metal
class Outputter {
private lazy var context: CIContext = {
guard
let device = MTLCreateSystemDefaultDevice(),
let queue = device.makeCommandQueue()
else {
print("WARNING: Using CPU-backed context. This is going to be very slow.")
return CIContext()
}
return CIContext(mtlCommandQueue: queue)
}()
func saveImageToTemporaryDirectory(_ image: UIImage, originalSize: CGSize, originalFileExtension: String?) -> URL? {
let fileExtension = originalFileExtension ?? "png" // Default to "png" if nil
let fileName = UUID().uuidString + "." + fileExtension
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
guard let ciImage = CIImage(image: image) else {
return nil
}
print("originalSize:", originalSize)
print("Start extent:", ciImage.extent)
// Apply color adjustments here.
print("End extent:", ciImage.extent)
let outputImage = ciImage.cropped(to: CGRect(origin: .zero, size: originalSize))
let colorSpace = outputImage.colorSpace ?? CGColorSpaceCreateDeviceRGB()
do {
if ["jpg", "jpeg"].contains(fileExtension.lowercased()) {
try context.writeJPEGRepresentation(of: outputImage, to: fileURL, colorSpace: colorSpace)
} else {
try context.writePNGRepresentation(of: outputImage, to: fileURL, format: .RGBA8, colorSpace: colorSpace)
}
} catch {
print("Export failed:", error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment