是否可以设置UIImageView
处理图像方向?当我将UIImageView
图像的方向设置为RIGHT(它是相机胶卷中的照片)时,图像会向右旋转,但是我想以拍摄时的正确方向显示它。
我知道我可以旋转图像数据,但是可以做得更优雅吗?
是否可以设置UIImageView
处理图像方向?当我将UIImageView
图像的方向设置为RIGHT(它是相机胶卷中的照片)时,图像会向右旋转,但是我想以拍摄时的正确方向显示它。
我知道我可以旋转图像数据,但是可以做得更优雅吗?
Answers:
如果我理解,您想要做的就是忽略UIImage的方向?如果是这样,那么您可以这样做:
UIImage *originalImage = [... whatever ...];
UIImage *imageToDisplay =
[UIImage imageWithCGImage:[originalImage CGImage]
scale:[originalImage scale]
orientation: UIImageOrientationUp];
因此,您要创建一个具有与原始像素相同的像素数据的新UIImage(通过其CGImage属性引用),但是要指定一个不会旋转数据的方向。
CGContext
使用CGBitmapContextCreate
(或使用UIGraphicsBeginImageContext
速记)创建适当大小的图片,使用CGContextRotateCTM
来设置旋转角度,drawInRect:
在UIImage
或上CGContextDrawImage
使用图片的CGImage
属性,然后使用UIGraphicsGetImageFromCurrentImageContext
(然后在)将上下文转换为图片,UIGraphicsEndImageContext
如果您使用UIKit创建上下文,或者CGBitmapContextCreateImage
如果您坚持使用Core Graphics。UIKit不是非常线程安全的,但是代码会更整洁。
您可以完全避免手工做的转换和缩放自己,在这个答案AN0的建议在这里:
- (UIImage *)normalizedImage {
if (self.imageOrientation == UIImageOrientationUp) return self;
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
[self drawInRect:(CGRect){0, 0, self.size}];
UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return normalizedImage;
}
UIImage方法size和drawInRect的文档明确声明它们考虑了方向。
我在这里将Anomie的答案中的代码(上面粘贴了suvish valsan的代码)转换为Swift:
func fixOrientation() -> UIImage {
if self.imageOrientation == UIImageOrientation.Up {
return self
}
var transform = CGAffineTransformIdentity
switch self.imageOrientation {
case .Down, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI));
case .Left, .LeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2));
case .Right, .RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));
case .Up, .UpMirrored:
break
}
switch self.imageOrientation {
case .UpMirrored, .DownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
case .LeftMirrored, .RightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGBitmapContextCreate(
nil,
Int(self.size.width),
Int(self.size.height),
CGImageGetBitsPerComponent(self.CGImage),
0,
CGImageGetColorSpace(self.CGImage),
UInt32(CGImageGetBitmapInfo(self.CGImage).rawValue)
)
CGContextConcatCTM(ctx, transform);
switch self.imageOrientation {
case .Left, .LeftMirrored, .Right, .RightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.height,self.size.width), self.CGImage);
default:
CGContextDrawImage(ctx, CGRectMake(0, 0, self.size.width,self.size.height), self.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = CGBitmapContextCreateImage(ctx)
let img = UIImage(CGImage: cgimg!)
return img;
}
(我更换了参数的所有occurenciesimage
用self
,因为我的代码是一个扩展UIImage
)。
编辑: Swift 3版本。
该方法返回一个可选参数,因为许多中间调用可能会失败,并且我不喜欢使用!
。
func fixOrientation() -> UIImage? {
guard let cgImage = self.cgImage else {
return nil
}
if self.imageOrientation == UIImageOrientation.up {
return self
}
let width = self.size.width
let height = self.size.height
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: width, y: height)
transform = transform.rotated(by: CGFloat.pi)
case .left, .leftMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.rotated(by: 0.5*CGFloat.pi)
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: height)
transform = transform.rotated(by: -0.5*CGFloat.pi)
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
guard let colorSpace = cgImage.colorSpace else {
return nil
}
guard let context = CGContext(
data: nil,
width: Int(width),
height: Int(height),
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue)
) else {
return nil
}
context.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width))
default:
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
}
// And now we just create a new UIImage from the drawing context
guard let newCGImg = context.makeImage() else {
return nil
}
let img = UIImage(cgImage: newCGImg)
return img;
}
(注意:Swift 3版本的odes可以在Xcode 8.1下进行编译,但尚未对其进行实际测试。在某处可能有错字,宽度/高度混合,等等。请随时指出/修复任何错误)。
func viewDidLoad
。该图像来自三星手机photos.google.com/share/…,具有270 CW方向的exif数据。我在这里使用它的方法let background: UIImage? = UIImage(named: "background_image")?.fixOrientation() backgroundImage.image = background
此方法首先检查UIImage的当前方向,然后按顺时针方向更改方向并返回UIImage。您可以将该图像显示为
self.imageView.image = rotationImage(currentUIImage)
func rotateImage(image:UIImage)->UIImage
{
var rotatedImage = UIImage();
switch image.imageOrientation
{
case UIImageOrientation.Right:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Down);
case UIImageOrientation.Down:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Left);
case UIImageOrientation.Left:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Up);
default:
rotatedImage = UIImage(CGImage:image.CGImage!, scale: 1, orientation:UIImageOrientation.Right);
}
return rotatedImage;
}
func rotateImage(image:UIImage) -> UIImage
{
var rotatedImage = UIImage()
switch image.imageOrientation
{
case .right:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .down)
case .down:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .left)
case .left:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .up)
default:
rotatedImage = UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: .right)
}
return rotatedImage
}
斯威夫特3.1
func fixImageOrientation(_ image: UIImage)->UIImage {
UIGraphicsBeginImageContext(image.size)
image.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? image
}
Swift中的UIImage扩展。实际上,您根本不需要进行所有翻转。这里是Objective-C原始的,但是我添加了尊重原始图像alpha的位(很粗略,但是它可以区分不透明图像和透明图像)。
// from https://github.com/mbcharbonneau/UIImage-Categories/blob/master/UIImage%2BAlpha.m
// Returns true if the image has an alpha layer
private func hasAlpha() -> Bool {
guard let cg = self.cgImage else { return false }
let alpha = cg.alphaInfo
let retVal = (alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast)
return retVal
}
func normalizedImage() -> UIImage? {
if self.imageOrientation == .up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, !self.hasAlpha(), self.scale)
var rect = CGRect.zero
rect.size = self.size
self.draw(in: rect)
let retVal = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return retVal
}
考虑到图像方向,这是一个可行的鳕鱼样本:
#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
CGAffineTransform rectTransform;
switch (img.imageOrientation)
{
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}
- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
//transform visible rect to image orientation
CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);
//crop image
CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
CGImageRelease(imageRef);
return result;
}
我将@Nicolas Miari答案的代码转换为Swift 3,以防有人需要
func fixOrientation() -> UIImage
{
if self.imageOrientation == UIImageOrientation.up {
return self
}
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: self.size.height)
transform = transform.rotated(by: CGFloat(M_PI));
case .left, .leftMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0);
transform = transform.rotated(by: CGFloat(M_PI_2));
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: self.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: self.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGContext(
data: nil,
width: Int(self.size.width),
height: Int(self.size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
)
ctx!.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))
default:
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = ctx!.makeImage()
let img = UIImage(cgImage: cgimg!)
return img;
}
imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any] let imageCaptured:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
始终为rightOrientation,并且该方法返回了图像:(
感谢Waseem05的Swift 3翻译,但是当我将它包装到UIImage扩展中并将其放置在父类的外部/下面时,他的方法才对我有用:
extension UIImage {
func fixOrientation() -> UIImage
{
if self.imageOrientation == UIImageOrientation.up {
return self
}
var transform = CGAffineTransform.identity
switch self.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: self.size.height)
transform = transform.rotated(by: CGFloat(M_PI));
case .left, .leftMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0);
transform = transform.rotated(by: CGFloat(M_PI_2));
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: self.size.height);
transform = transform.rotated(by: CGFloat(-M_PI_2));
case .up, .upMirrored:
break
}
switch self.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: self.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: self.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1);
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
let ctx = CGContext(
data: nil,
width: Int(self.size.width),
height: Int(self.size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
)
ctx!.concatenate(transform);
switch self.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
// Grr...
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))
default:
ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
break;
}
// And now we just create a new UIImage from the drawing context
let cgimg = ctx!.makeImage()
let img = UIImage(cgImage: cgimg!)
return img;
}
}
然后用:
let correctedImage:UIImage = wonkyImage.fixOrientation()
一切都很好!当我们不需要前置/后置摄像头和上/下/左/右设备方向元数据时,Apple应该使丢弃方向更加容易。
如果您需要旋转并固定延伸方向以下的图像方向,将很有用。
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
//Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
//Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap: CGContext = UIGraphicsGetCurrentContext()!
//Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
//Rotate the image context
bitmap.rotate(by: (degrees * CGFloat.pi / 180))
//Now, draw the rotated/scaled image into the context
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
public func fixedOrientation() -> UIImage {
if imageOrientation == UIImageOrientation.up {
return self
}
var transform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case UIImageOrientation.down, UIImageOrientation.downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat.pi)
break
case UIImageOrientation.left, UIImageOrientation.leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat.pi/2)
break
case UIImageOrientation.right, UIImageOrientation.rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: -CGFloat.pi/2)
break
case UIImageOrientation.up, UIImageOrientation.upMirrored:
break
}
switch imageOrientation {
case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
transform.translatedBy(x: size.width, y: 0)
transform.scaledBy(x: -1, y: 1)
break
case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
transform.translatedBy(x: size.height, y: 0)
transform.scaledBy(x: -1, y: 1)
case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
break
}
let ctx: CGContext = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.concatenate(transform)
switch imageOrientation {
case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
break
}
let cgImage: CGImage = ctx.makeImage()!
return UIImage(cgImage: cgImage)
}
}
extension UIImage {
func fixImageOrientation() -> UIImage {
UIGraphicsBeginImageContext(self.size)
self.draw(at: .zero)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? self
}
}
称之为:imageView.image?.fixImageOrientation()
或UIImage(named: "someImage").fixImageOrientation()
祝你好运!
汤米的答案的Swift 3.0版本
let imageToDisplay = UIImage.init(cgImage: originalImage.cgImage!, scale: originalImage.scale, orientation: UIImageOrientation.up)
灵感来自@Aqua Answer .....
在目标C中
- (UIImage *)fixImageOrientation:(UIImage *)img {
UIGraphicsBeginImageContext(img.size);
[img drawAtPoint:CGPointZero];
UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (newImg) {
return newImg;
}
return img;
}