元ネタ (Objective-C)
「 UIImage で作った JPEG の向きがおかしいんだけど」
「 imageOrientation というプロパティで正しい方向を持ってる。それを使って、強制的に方向を変換することもできる」
というやりとり。
Objective-C でカテゴリ拡張を行い fixOrientation
というメソッドを足す例を示している。
同様の Gist: https://gist.github.com/alex-cellcity/1531596
Swift 版
せっかくなので、全く同じメソッドを Swift
で書き直してみました。
UIImage+fixOrientation.swift
//
// UIImage+fixOrientation.swift
//
import UIKit
extension UIImage {
func fixOrientation () -> UIImage {
if self.imageOrientation == UIImageOrientation.Up {
return self
}
var transform = CGAffineTransformIdentity
typealias o = UIImageOrientation
let width = self.size.width
let height = self.size.height
switch (self.imageOrientation) {
case o.Down, o.DownMirrored:
transform = CGAffineTransformTranslate(transform, width, height)
case o.Left, o.LeftMirrored:
transform = CGAffineTransformTranslate(transform, width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
case o.Right, o.RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
default: // o.Up, o.UpMirrored:
break
}
switch (self.imageOrientation) {
case o.UpMirrored, o.DownMirrored:
transform = CGAffineTransformTranslate(transform, width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case o.LeftMirrored, o.RightMirrored:
transform = CGAffineTransformTranslate(transform, height, 0)
transform = CGAffineTransformScale(transform, -1, 1)
default: // o.Up, o.Down, o.Left, o.Right
break
}
let cgimage = self.CGImage
let ctx = CGBitmapContextCreate(nil, UInt(width), UInt(height),
CGImageGetBitsPerComponent(cgimage), 0,
CGImageGetColorSpace(cgimage),
CGImageGetBitmapInfo(cgimage))
switch (self.imageOrientation) {
case o.Left, o.LeftMirrored, o.Right, o.RightMirrored:
CGContextDrawImage(ctx, CGRectMake(0, 0, height, width), cgimage)
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, width, height), cgimage)
}
let cgimg = CGBitmapContextCreateImage(ctx)
let img = UIImage(CGImage: cgimg)
return img!
}
}