问题
I have written this code to capture an image using the AVFoundation library in Swift:
@IBAction func cameraButtonWasPressed(sender: AnyObject) {
if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection){
(imageSampleBuffer : CMSampleBuffer!, _) in
let imageDataJpeg = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer)
var pickedImage: UIImage = UIImage(data: imageDataJpeg)!
let library = ALAssetsLibrary()
library.writeImageToSavedPhotosAlbum(pickedImage.CGImage,
metadata:nil,
completionBlock:nil)
}
}
}
It works fine, but when I go to the photo library the image shows rotated 90 degrees counter clockwise.
Can someone give me an hint on where to dig to fix this?
回答1:
You should be using a slightly different writeImage
method:
(1) get the orientation from the UIImage imageOrientation
property (an enum), and cast it to ALAssetOrientation (an enum with the same Int values as UIImageOrientation)
var orientation : ALAssetOrientation = ALAssetOrientation(rawValue:
pickedImage.imageOrientation.rawValue)!
(2) use a similar-but-different method on ALAssetLibrary
library.writeImageToSavedPhotosAlbum(
pickedImage.CGImage,
orientation: orientation,
completionBlock:nil)
This works for me in Objective-C ... I have had a quick go at translating to Swift (as above) but I am getting compiler warnings.
Cannot invoke 'writeImageToSavedPhotosAlbum' with an argument list of type '(CGImage!, orientation: ALAssetOrientation, completionBlock: NilLiteralConvertible)'
Perhaps you could try (I don't have the time to construct a full AVFoundation pipeline in Swift to test this definitively)
If you can't get that to work, the other solution is to extract the exif metadata from the sampleBuffer and pass it through to the method you are already using
library.writeImageToSavedPhotosAlbum(pickedImage.CGImage,
metadata:nil,
completionBlock:nil
回答2:
Maybe this Swift code can help you.
//correctlyOrientedImage.swift
import UIKit
extension UIImage {
public func correctlyOrientedImage() -> UIImage {
if self.imageOrientation == UIImageOrientation.Up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
self.drawInRect(CGRectMake(0, 0, self.size.width, self.size.height))
var normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return normalizedImage;
}
}
I saw it somewhere in stack overflow and incorporated in my project as well.
来源:https://stackoverflow.com/questions/28225378/uiimage-orientation-swift