iOS-CoreImage簡單使用

來源:互聯網
上載者:User

標籤:

CoreImage是一個映像架構,它基於OpenGL頂層建立,底層則用著色器來處理映像,這意味著它利用了GPU基於硬體加速來處理映像。CoreImage中有很多濾鏡,它們能夠一次給予一張映像或者視訊框架多種視覺效果。而且濾鏡可以串連起來組成一個濾鏡鏈,把濾鏡效果疊加起來處理映像。

CoreImage架構最常用的類:


* CIImage

儲存映像資料的類,可以通過UIImage,影像檔或者像素資料來建立,包括未處理的像素資料如:

- imageWithCVPixelBuffer:

- imageWithData:

方法等等。

也可以通過映像資料類比如UIImage,CGImageRef等等。


* CIFilter

濾鏡類,這個架構中對圖片屬性進行細節處理的類。它對所有的像素進行操作,用一些鍵-值設定來決定具體操作的程度。


* CIContext

上下文類,如CoreGraphics以及CoreData中的上下文用於處理繪製渲染以及處理託管對象一樣,CoreImage的上下文也是實現對影像處理的具體對象。

這裡需要注意的是在Context建立的時候,我們需要給它設定為是基於GPU還是CPU。(這裡使用GPU)

基於GPU的話,處理速度更快,因為利用了GPU硬體的並行優勢。但是GPU受限於硬體紋理尺寸,而且如果你的程式在後台繼續處理和儲存圖片的話,那麼需要使用CPU,因為當app切換到後台狀態時GPU處理會被打斷。

 

使用步驟:

0.匯入CIImage圖片

    CIImage *ciImage = [[CIImage alloc]initWithImage:[UIImage imageNamed:@"test.jpg"]];

1.建立出Filter濾鏡

    CIFilter *filterOne = [CIFilter filterWithName:@"CIPixellate"];
    [filterOne setValue:ciImage forKey:kCIInputImageKey];
    [filterOne setDefaults];

    CIImage *outImage = [filterOne valueForKey:kCIOutputImageKey];

2.用CIContext將濾鏡中的圖片渲染出來

    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef cgImage = [context createCGImage:outImage fromRect:[outImage extent]];

3.匯出圖片

    UIImage *showImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);

4.載入圖片

   _image.image = showImage;

 

 如果要使用組合濾鏡

在步驟1中設定組合濾鏡,只需要將上一個濾鏡的輸出變為下一個濾鏡的輸入就行了

    //第一個濾鏡
    CIFilter *filterOne = [CIFilter filterWithName:@"CIPixellate"];
    [filterOne setValue:ciImage forKey:kCIInputImageKey];
    [filterOne setDefaults];
    CIImage *outImage = [filterOne valueForKey:kCIOutputImageKey];
    //第二個濾鏡
    CIFilter *filterTwo = [CIFilter filterWithName:@"CIHueAdjust"];
    [filterTwo setValue:outImage forKey:kCIInputImageKey];
    [filterTwo setDefaults];
    [filterTwo setValue:@(1.f) forKey:kCIInputAngleKey];
    CIImage *outputImage = [filterTwo valueForKey:kCIOutputImageKey];

 記住渲染的時候,步驟2,要將最後輸出的CIImage傳入

 

    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef cgImage = [context createCGImage:outputImage fromRect:[outImage extent]];

iOS-CoreImage簡單使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.