Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UIImage.imageOrientation not honored #83

Open
actow opened this issue Nov 6, 2021 · 1 comment
Open

UIImage.imageOrientation not honored #83

actow opened this issue Nov 6, 2021 · 1 comment

Comments

@actow
Copy link

actow commented Nov 6, 2021

Images loaded by UIImagePickerController don't always have .imageOrientation set to UIImage.Orientation.up.

Transformations need to be applied accordingly before encoding them into the video.

@actow
Copy link
Author

actow commented Nov 6, 2021

Very rough, not well tested code that applies the orientation.

extension UIImage {
  func fixedOrientation() -> UIImage {
    guard imageOrientation != .up else {
      return self
    }

    guard let cgImage = cgImage else {
      return self
    }

    let w = size.width
    let h = size.height

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

    guard let ctx = CGContext(data: nil, width: Int(w), height: Int(h), bitsPerComponent: 8, bytesPerRow: Int(w) * 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
      return self
    }

    switch imageOrientation {
    case .down, .downMirrored:
      ctx.translateBy(x: w, y: h)
      ctx.rotate(by: .pi)
    case .left, .leftMirrored:
      ctx.translateBy(x: w, y: 0)
      ctx.rotate(by: .pi / 2.0)
    case .right, .rightMirrored:
      ctx.translateBy(x: 0, y: h)
      ctx.rotate(by: -.pi / 2.0)
    case .up, .upMirrored:
      break
    @unknown default:
      return self
    }

    switch imageOrientation {
    case .upMirrored, .downMirrored:
      ctx.translateBy(x: size.width, y: 0)
      ctx.scaleBy(x: -1, y: 1)
    case .leftMirrored, .rightMirrored:
      ctx.translateBy(x: size.height, y: 0)
      ctx.scaleBy(x: -1, y: 1)
    case .up, .down, .left, .right:
      break
    @unknown default:
      return self
    }

    switch imageOrientation {
    case .left, .leftMirrored, .right, .rightMirrored:
      ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: h, height: w))
    default:
      ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
    }

    guard let resultCgImage: CGImage = ctx.makeImage() else {
      return self
    }

    return UIImage(cgImage: resultCgImage)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant