Core Image 提供了強大的圖像處理能力,其中 CIColorControls 濾鏡可以用來調整圖像的亮度、對比度與飽和度。以下示範如何封裝一個方法,將傳入的圖像調亮。
- (UIImage *)getBrighterImage:(UIImage *)originalImage {
UIImage *brighterImage;
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [CIImage imageWithCGImage:originalImage.CGImage];
CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
[lighten setValue:inputImage forKey:kCIInputImageKey];
// inputBrightness 為 0.3,數值越大圖像越亮
[lighten setValue:@(0.3) forKey:@"inputBrightness"];
CIImage *result = [lighten valueForKey:kCIOutputImageKey];
CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];
brighterImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return brighterImage;
}
CIColorControls 除了 inputBrightness(亮度),還支援 inputContrast(對比度)與 inputSaturation(飽和度)。CIContext 將處理後的 CIImage 轉回 CGImageRef,再包裝成 UIImage。CGImageRef 由我們手動建立,記得在最後呼叫 CGImageRelease 釋放,避免記憶體洩漏。透過這個方法,只要調整 inputBrightness 的數值,就能輕鬆地讓圖像變亮或變暗。