LoginSignup
33
31

More than 5 years have passed since last update.

カメラで撮った写真を加工する際の注意

Posted at

カメラで撮った写真からサムネイルを生成する際に、UIImage->CGImage->UIImageというふうに変換した。その際、画像が意図せずに回転する現象に遭遇した。
(ex. iPhoneを縦にして撮る->生成したサムネイルが90度回転した状態になる)
以下、原因と対処に関するメモ。

カメラで撮った写真(UIImage)は、imageOrientationプロパティに写真の向きに関する情報を保存している。
(ref. http://horsewater.blog112.fc2.com/blog-entry-25.html)
この情報により写真の向きは適切に保たれるが、この情報がCGImageを経由してUIImageを加工した際に失われる場合がある。

# (注) UIImageのカテゴリとして実装しているため、self.imageOrientationでアクセスできる
NSLog(@"Orientation(Before):%@", [NSNumber numberWithInteger:self.imageOrientation]);
CGRect croppedSquare = CGRectMake(x, y, length, length);
CGImageRef ref = CGImageCreateWithImageInRect(self.CGImage, croppedSquare);

UIImage *croppedImage = [UIImage imageWithCGImage:ref];
NSLog(@"Orientation(After):%@", [NSNumber numberWithInteger:croppedImage.imageOrientation]);
CGImageRelease(ref);

(ログ出力)
2014-08-08 02:19:40.242 bribum[4536:60b] Orientation(Before):3
2014-08-08 02:19:40.244 bribum[4536:60b] Orientation(After):0

向きの情報を失わなずに加工したUIImageを取得するためには、[UIImage imageWithCGImage:]ではなく[UIImage imageWithCGImage:scale:orientation:]を使用して
元の画像の向きを教えてやる必要がある。

NSLog(@"Orientation(Before):%@", [NSNumber numberWithInteger:self.imageOrientation]);
CGRect croppedSquare = CGRectMake(x, y, length, length);
CGImageRef ref = CGImageCreateWithImageInRect(self.CGImage, croppedSquare);

UIImage *croppedImage = [UIImage imageWithCGImage:ref
                                            scale:[UIScreen mainScreen].scale
                                      orientation:self.imageOrientation];
NSLog(@"Orientation(After):%@", [NSNumber numberWithInteger:croppedImage.imageOrientation]);
CGImageRelease(ref);

(ログ出力)
2014-08-08 02:41:25.350 bribum[4551:60b] Orientation(Before):3
2014-08-08 02:41:25.354 bribum[4551:60b] Orientation(After):3
33
31
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
31