Created
December 4, 2022 14:59
-
-
Save bobgodwinx/1f96885707170be141af2f712989dc08 to your computer and use it in GitHub Desktop.
ChatGPT_Applying_Instagram_Filters_in_Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Foundation | |
import CoreImage | |
import MetalPerformanceShaders | |
// MARK: - Filter Types | |
enum FilterType { | |
case clarendon | |
case gingham | |
case juno | |
case lark | |
case mayfair | |
case sierra | |
case valencia | |
case walden | |
var filter: CIFilter { | |
switch self { | |
case .clarendon: | |
let filter = CIFilter(name: "CIPhotoEffectChrome")! | |
return filter | |
case .gingham: | |
let filter = CIFilter(name: "CIColorMonochrome")! | |
filter.setValue(CIColor(red: 0.9, green: 0.9, blue: 0.9), forKey: "inputColor") | |
filter.setValue(1.0, forKey: "inputIntensity") | |
return filter | |
case .juno: | |
let filter = CIFilter(name: "CIColorControls")! | |
filter.setValue(0.5, forKey: "inputSaturation") | |
filter.setValue(1.0, forKey: "inputBrightness") | |
filter.setValue(1.5, forKey: "inputContrast") | |
return filter | |
case .lark: | |
let filter = CIFilter(name: "CIPhotoEffectTransfer")! | |
return filter | |
case .mayfair: | |
let filter = CIFilter(name: "CIPhotoEffectProcess")! | |
return filter | |
case .sierra: | |
let filter = CIFilter(name: "CISepiaTone")! | |
filter.setValue(1.0, forKey: "inputIntensity") | |
return filter | |
case .valencia: | |
let filter = CIFilter(name: "CIPhotoEffectFade")! | |
return filter | |
case .walden: | |
let filter = CIFilter(name: "CIPhotoEffectInstant")! | |
return filter | |
} | |
} | |
} | |
// MARK: - Image Filtering | |
struct FilteredImage { | |
let image: CGImage | |
let filter: CIFilter | |
} | |
class ImageFilter { | |
private let device: MTLDevice | |
private let commandQueue: MTLCommandQueue | |
init(device: MTLDevice) { | |
self.device = device | |
self.commandQueue = device.makeCommandQueue()! | |
} | |
func applyFilter(_ filterType: FilterType, to inputImage: CGImage) -> FilteredImage { | |
// Create CIImage from input CGImage | |
let inputCIImage = CIImage(cgImage: inputImage) | |
// Apply filter to CIImage | |
let filter = filterType.filter | |
filter.setValue(inputCIImage, forKey: kCIInputImageKey) | |
let outputCIImage = filter.outputImage! | |
// Create CGImage from filtered CIImage | |
let context = CIContext(mtlDevice: device) | |
let outputCGImage = context.createCGImage(outputCIImage, from: outputCIImage.extent)! | |
return FilteredImage(image: outputCGImage, filter: filter) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment