【iPhone】GPUImageで2枚の画像をBlendする方法

概要

GPUImageを使用して、2枚の画像をBlendする方法。
Blend方法は何種類かあり、PhotoShopにもある下記のようなBlendなどが可能。

GPUImageMultiplyBlendFilter: Applies a multiply blend of two images
GPUImageOverlayBlendFilter: Applies an overlay blend of two images
GPUImageColorBurnBlendFilter: Applies a color burn blend of two images
GPUImageScreenBlendFilter: Applies a screen blend of two images
GPUImageExclusionBlendFilter: Applies an exclusion blend of two images
GPUImageHardLightBlendFilter: Applies a hard light blend of two images
GPUImageSoftLightBlendFilter: Applies a soft light blend of two images
GPUImageAlphaBlendFilter: Blends the second image over the first, based on the second's 

今回は上記のoverlayを試してみます。

■GPUImage
https://github.com/BradLarson/GPUImage

方法

下記のように実装します。

UIImage *originImage = [UIImage imageNamed:@"Lenna.bmp"]; //元画像
UIImage *layerImage = [UIImage imageNamed:@"blueImage.png"]; //合成する画像(今回は青い画像 )
GPUImagePicture* picture1 = [[GPUImagePicture alloc] initWithImage:originImage];
GPUImagePicture* picture2 = [[GPUImagePicture alloc] initWithImage:layerImage];

GPUImageOverlayBlendFilter* blendFilter = [[GPUImageOverlayBlendFilter alloc] init];
  
[picture1 addTarget:blendFilter];
[picture1 processImage];
[picture2 addTarget:blendFilter];
[picture2 processImage];

// 結果画像
UIImage* blendImage = [blendFilter imageFromCurrentlyProcessedOutputWithOrientation:originImage.imageOrientation];

・元画像
f:id:unibo:20131115232013j:plain:w200:h200
・結果
f:id:unibo:20131115232152p:plain:w200:h200

合成結果を出力する際に画像の向きを指定することで、結果画像が回転するのを防いでいます。

// 加工前の画像の向きを渡しているため回転しない
UIImage* blendImage = [blendFilter imageFromCurrentlyProcessedOutputWithOrientation:originImage.imageOrientation];

下記の方法だと端末を横にした状態で処理を実行すると画像が回転します。

// 端末を横にした状態で処理を実行すると画像が回転する
UIImage* blendImage = [blendFilter imageFromCurrentlyProcessedOutput];

今回はoverlayを試しましたが、その他のBlend方法も同じように実装すればできるはずです。
上記のBlendをうまく使えばオリジナルのフィルターを作成することが可能になります。
カメラアプリを開発する際はぜひ試してみてください!

おすすめの書籍

Effective Objective-C 2.0

Effective Objective-C 2.0

定番のEffectiveシリーズ!